Suppose you have a WCF service with
[ServiceBehavior(
IncludeExceptionDetailInFaults = true,
InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple,
UseSynchronizationContext = false)]
What difference does using the async/await pattern for service operations under this implementation make? Don’t the service calls get pooled and possibly executed asynchronously even if async/await is not used? Even after reading lots of msdn and blog articles, the above scenario is still not clear to me and I would asyncify my operations to be safe.
No.
ConcurrencyMode.Multiplewill permit multiple threads to execute calls simultaneously, but that’s not the same as asynchronous processing.Consider a single synchronous request: a single thread will take the request and execute it all the way until it is complete. If that thread blocks, then you have a blocked thread waiting for that request to complete. You can specify
ConcurrencyMode.Multipleto allow other threads to come in and do other calls without blocking on other requests.Now consider a single asynchronous request: a single thread will take the request and begin executing it. Instead of blocking, that thread will “await”, which returns the thread to the thread pool until the asynchronous operation completes. This means there is no blocking thread on that request. When the method resumes after its
await, some thread from the thread pool will be used to continue the request (and eventually one of those threads will complete the request).The bottom line is that
asyncon the server side allows greater scale than synchronous code, because asynchronous operations have lower overhead than threads.ConcurrencyModedeals with a different question: it’s about how threadsafe your service implementation is. If you can have multiple calls concurrently, you should specifyConcurrencyMode.Multiple. If you have naturally asynchronous operations, you should make themasync. And if you’re threadsafe and naturally asynchronous, you should do both.