Callbacks and Client Safety

There are quite a few cases when a client might receive concurrent callbacks. If the client provided a callback reference to multiple services, those services could call back concurrently to the client. But even with a single callback reference, the service might launch multiple threads and use all of them to call on that single reference. Duplex callbacks enter the client on worker threads and might corrupt the client state if done concurrently without synchronization. The client must synchronize access to its own in-memory state, but also to any resources the callback thread might access. Similar to a service, a callback client can use either manual or declarative synchronization. The CallbackBehavior attribute introduced in Chapter 6 offers the ConcurrencyMode and the UseSynchronizationContext properties:

[AttributeUsage(AttributeTargets.Class)]
public sealed class CallbackBehaviorAttribute : Attribute,...
{
   public ConcurrencyMode ConcurrencyMode
   {get;set;}
   public bool UseSynchronizationContext
   {get;set;}
}

Both of these properties default to the same values as with the ServiceBehavior attribute and behave in a similar manner. For example, the default of the ConcurrencyMode property is ConcurrencyMode.Single, so these two definitions are equivalent:

class MyClient : IMyContractCallback
{...}

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
class MyClient : IMyContractCallback
{...}

Callbacks with ConcurrencyMode.Single

When the callback ...

Get Programming WCF Services 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.