I am implementing my first REST service in .NET 4 and have encountered something unexpected. It seems that I do not understand the underlining workings of Microsoft's ServiceModel, but could not find the answer in the traditional way.
To implement my web service I was following the steps in this tutorial: http://blogs.msdn.com/b/endpoint/archive/2010/01/06/introducing-wcf-webhttp-services-in-net-4.aspx
The service works. What surprised me was that Application_BeginRequest and Application_EndRequest in Global.asax are called by different threads. Looking at stack trace it appears that these threads are based in some kind of thread pool.
Without doing some refactorings this is a problem for us since we were always assuming that a single request would always run on the same thread, due to which we were keeping some variables stored in the thread local storage. The variables are initialized in Application_BeginRequest and released in Application_EndRequest. It appears that with ServiceModel this is not the right approach.
My questions are:
Thank you.
Thread pool threads are background threads. Each thread uses the default stack size, runs at the default priority, and is in the multithreaded apartment. Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused.
Threadpool is the native software level thread management system for Dotnet runtime. It is also the queuing mechanism for all the incoming requests. There is no separate request queuing mechanism in Dotnet core besides the threadpool. On the hardware level we typically have 1 thread per core of the CPU.
BackgroundWorker Class This class is essentially a wrapper for the ThreadPool class and uses a thread pool in its implementation.
QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
One thing I'd suggest is to consider using the WCF hooks rather than the Application_BeginRequest and Application_EndRequest methods. Four instance, here are four of the more useful hooks:
AfterReceiveRequest -> BeforeCall -> Method call -> AfterCall -> BeforeSendReply
There hooks are pretty powerful. You an inspect parameters before your method is called (centralize some logging to one place) and do all sorts of other useful things. These are not the only hooks available, there are some others I use as well. For instance GetInstance allows me to override creation of the service class object (so you can use dependency injection frameworks, etc).
When I use the per call concurrency mode, these hooks plus the method call itself ALL get called on the same thread. Hope this helps. I can provide links to implementing these hooks if you like.
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With