Concurrency Management

  1. Always provide thread-safe access to:

    1. Service in-memory state with sessionful or singleton services

    2. Client in-memory state during callbacks

    3. Shared resources

    4. Static variables

  2. Prefer ConcurrencyMode.Single (the default). It enables transactional access and provides thread safety without any effort.

  3. Keep operations on single-mode sessionful and singleton services short in order to avoid blocking other clients for long.

  4. When using ConcurrencyMode.Multiple, you must use transaction auto-completion.

  5. Consider using ConcurrencyMode.Multiple on per-call services to allow concurrent calls.

  6. Transactional singleton service with ConcurrencyMode.Multiple must have ReleaseServiceInstanceOnTransactionComplete set to false:

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
                     ConcurrencyMode = ConcurrencyMode.Multiple,
                     ReleaseServiceInstanceOnTransactionComplete = false)]
    class MySingleton : IMyContract
    {...}
  7. Never self-host on a UI thread, and have the UI application call the service.

  8. Never allow callbacks to the UI application that called the service unless the callback posts the call using SynchronizationContext.Post( ).

  9. When supplying the proxy with both synchronous and asynchronous methods, apply the FaultContract attribute only to synchronous methods.

  10. Keep asynchronous operations short. Do not equate asynchronous calls with lengthy operations.

  11. Do not mix transactions with asynchronous calls.

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.