Controlling the Synchronization Context
The synchronization context is invisible state that flows around making sure that the proper threading model is being used with requests. Windows Forms applications, for example, require that calls be made on a particular thread and the synchronization context makes sure that that thread marshalling takes place. Rarely though, you need to manually intervene in this process. Access to your synchronization context is provided through static variables. Here is some code showing how to make a call while bypassing the synchronization context that is current in place.
SynchronizationContext oldContext = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
proxy.Open();
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
There's a tricky example of manually controlling the synchronization context. By default, we want service calls to work correctly when made from a Windows Forms application. The synchronization context is used while opening up a proxy to make sure that everything happens on the right thread. On the other hand, IIS hosted applications are not compatible with that thread model, so when we're running in a hosted environment we don't use the synchronization context. This normally isn't a problem because you don't have a user interface running on the server.
If you make a call out from your hosted service using a composite duplex binding, then you're opening up a new service host inside of your service host inside of IIS. This nested service host doesn't realize that it too is web hosted and tries to use the forbidden synchronization context. IIS will eventually bomb because of this thread misuse unless you use something like the code snippet above. There are other reasons why you shouldn't open up new service hosts inside of a web-hosted service, but it makes a good example.
Next time: Format for Configuring HTTP and TCP Activation
Comments
Anonymous
November 28, 2006
What's wrong with the following code? The error message when you try this is better than it used to beAnonymous
November 28, 2006
Workflow/BPM/WCF/SOA David Chappell presents arguments both pro and con as to whether Microsoft qualifiesAnonymous
December 11, 2007
Workflow/BPM/WCF/SOA David Chappell presents arguments both pro and con as to whether Microsoft qualifiesAnonymous
December 03, 2008
Workflow/BPM/WCF/SOA David Chappell presents arguments both pro and con as to whether Microsoft qualifies as a BPM vendor. Personally, I think the answer is yes, especially when WF is intergrated into BizTalk 200x and other products. Nicholas Allan continues