Custom Service Synchronization Contexts

While a synchronization context is a general-purpose pattern out of the box, .NET only implements a handful of useful ones, with the two useful ones being the Windows Forms synchronization context and the WPF synchronization context (there is also the default implementation that uses the .NET thread pool). As it turns out, the ability to automatically marshal calls to a custom synchronization context is one of the most powerful extensibility mechanisms in WCF.

The Thread Pool Synchronizer

There are two aspects to developing a custom service synchronization context: the first is implementing a custom synchronization context, and the second is installing it or even applying it declaratively on the service. ServiceModelEx contains my ThreadPoolSynchronizer class, defined as:

public class ThreadPoolSynchronizer : SynchronizationContext,IDisposable
   public ThreadPoolSynchronizer(uint poolSize);
   public ThreadPoolSynchronizer(uint poolSize,string poolName);

   public void Dispose();
   public void Close();
   public void Abort();

   protected Semaphore CallQueued

Implementing a custom synchronization context has nothing to do with WCF and is therefore not discussed in this book, although the implementation code is available with ServiceModelEx.

ThreadPoolSynchronizer marshals all calls to a custom thread pool, where the calls are first queued up, then multiplexed on the available threads. The size of the pool is provided as a construction parameter. If ...

Get Programming WCF Services, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.