Programming WCF Services



Instance Management and Concurrency

Service-instance thread safety is closely related to the service-instancing mode. A per-call service instance is thread-safe by definition because each call gets its own dedicated instance.

Service Concurrency Mode

Concurrent access to the service instance is governed by the ConcurrencyMode property of the ServiceBehavior attribute: public enum ConcurrencyMode { Single, Reentrant, Multiple } [AttributeUsage(AttributeTargets.Class)]

Instances and Concurrent Access

Using the same proxy, a single client can issue multiple concurrent calls to the service. The client could use multiple threads to invoke calls on the service, or the client could issue one-way calls in rapid succession.

Resources and Services

Synchronizing access to the service instance using ConcurrencyMode.Single or an explicit synchronization lock only manages concurrent access to the service instance state itself.

Resource Synchronization Context

Incoming service calls execute on worker threads. These threads are managed by WCF and are unrelated to any service or resource threads. This means that by default the service cannot rely on any kind of thread affinity.

Service Synchronization Context

The programming techniques showed so far put the onus of accessing the resource on the correct thread squarely on the service or resource developer.

Custom Service Synchronization Context

While synchronization context is a general-purpose pattern, out of the box, .NET 2.0 and WCF only implement a single occurrence of it: the Windows Forms synchronization context. Developing a custom service synchronization context has two aspects.

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.

Callbacks and Synchronization Context

Similar to a service invocation, the callback may need to access resources that rely on some kind of thread(s) affinity.

Asynchronous Calls

When a client calls a service, usually the client is blocked while the service executes the call, and control returns to the client only when the operation completes its execution and returns.

 

Read more