Service created and released on two different threads

Topics: Web Api
Mar 19, 2012 at 10:24 PM

This is something that I did not expect - we have some code executing when service instance is created and when it is released. It appears that this is done on two different threads, which is making it somewhat difficult for us.

Here is a very simplified version of what is happenning:

















public class MyApiConfiguration : WebApiConfiguration 








      this.CreateInstance = this.OnCreateInstance;



      this.ReleaseInstance = this.OnReleaseInstance;




protected virtual object OnCreateInstance(Type type, InstanceContext instanceContext, HttpRequestMessage requestMessage)




     int t1 = Thread.CurrentThread.ManagedThreadId;



     return Activator.CreateInstance(type);




protected virtual void OnReleaseInstance(InstanceContext instanceContext, object instance)




     int t2 = Thread.CurrentThread.ManagedThreadId;



When using  custom configuration and putting breakpoint in Create / Release methods one can see that t1 and t2 point to two different threads.

Any reasons for that and is there any way to enforce the same thread being used?




Mar 19, 2012 at 10:34 PM

Everything is done doing async calls so I would imagine this happening.

No other input than that from me, sorry.

Mar 20, 2012 at 2:59 PM

How am I supposed to do cleanup then?

Even more problematic - it looks like serialization of the load is also done on a different thread. I have some lazy-loaded properties that need database quering - and they can't be populated because my whole environment is different.

Mar 20, 2012 at 3:19 PM

What cant you cleanup? Things attached to the thread? That's the problem with thread based storage is dispose isn't called. You'll have to figure out a different way to store whatever it is.

I don't know what you are doing with serialization, authentication? I don't know why you're having a problem so I can't assist.

Mar 20, 2012 at 5:33 PM

I don't do anything with serialization - system does. My service method is returning the instance of the class. WebApi infrastructure is serializing it into JSON behind the scene. Well, this "behind" is really behind the scene - on a different thread! When it tries to serialize lazy-loaded property - then getter of that property needs to access the database. But because it is on a different thread - it has no settings to do so.