wcfthreadstatic

ThreadStatic - Does a WCF method call execute exclusively on a single thread?


One of the libraries our WCF service references uses a ThreadStatic variable. The service method sets its value at the beginning of each call. I'm wondering if this is safe - in other words, can we guarantee that exactly one thread will be used exclusively for the entire call? Or is it possible that a call could begin on one worker thread and finish on another? Or could a worker thread be swapped to a different method call and then back again?

We are using the defaults of ConcurrencyMode.Single and InstanceContextMode.PerSession.

EDIT

The only information I have been able to find so far is this blog post, which states that it is possible for a call to be processed by multiple threads:

http://blogs.microsoft.co.il/blogs/applisec/archive/2009/11/23/wcf-thread-affinity-and-synchronization.aspx

Is this guy correct? Is there any definitive information from Microsoft?


Solution

  • If you are not sure you can always use the CallContext class: CallContext.LogicalSetData CallContext.LogicalGetData

    While ThreadStatic won't work if the thread did change, the Logical CallContext is passed around in .NET, even if you would create your own new thread/task.