Service Synchronization Context
The programming techniques shown so far put the onus of accessing the resource on the
correct thread squarely on the service or resource developer. It would be preferable if the
service had a way of associating itself with a particular synchronization context, and could
have WCF detect that context and automatically marshal the call from the worker thread to
the associated service synchronization context. In fact, WCF lets you do just that. You can
instruct WCF to maintain an affinity between all service instances from a particular host
and a specific synchronization context. The ServiceBehavior
attribute offers the UseSynchronizationContext
Boolean property, defined as:
[AttributeUsage(AttributeTargets.Class)] public sealed class ServiceBehaviorAttribute : ... { public bool UseSynchronizationContext {get;set;} //More members }
The affinity between the service type, its host, and a synchronization context is locked
in when the host is opened. If the thread opening the host has a synchronization context and
UseSynchronizationContext
is true
, WCF will establish an affinity between that synchronization context and
all instances of the service hosted by that host. WCF will automatically marshal all
incoming calls to the service's synchronization context. All the thread-specific information
stored in the TLS, such as the client's transaction or the security information (discussed
in Chapter 10), will be marshaled correctly to the synchronization context. ...
Get Programming WCF Services, 2nd 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.