Scenario: Client application invokes a Duplex WCF service, and WCF service can invoke multiple callbacks at a time.
Problem: You notice that the callback operations are executed sequentially even though they are marked as one way operations.
Cause: Callback operations are handled on a separate worker thread at client application. By default, the concurrency mode is Single so only one thread is spawned to process callbacks; as a result, if there are more than one callback operations, they get called sequentially.
Repro of the problem: WCF service namely DuplexService implements an interface IDuplexService that has a callback contract where there are two callback operations marked as a one way operation.
> operation Reply is designed to take more time by putting it to sleep
> Second operation Myop works normally just to put a statement on console.
While making a callback from the service, first a call is made to reply operation (long time of execution) and then a repeated call is made to the other operation that doesn’t take much time.
WCF client Duplex client calls the WCF service and calls the “Hello” method of this service. It’s a console client and implements the callback contract through one of its classes that provides instance context to serve the callback calls from service.
Expected behavior: The Callback operations should be processed in parallel. So, here is what we get instead of getting a print of the second operation on the console first and then that of the first operation
To resolve the issue, mark the class that implements the callback with the callback behavior as below,
Above will allow client application to spawn multiple background threads and process callbacks concurrently. Here is what we get now with above change:
Story inside the hood: When a callback is made from the service to client, only one thread is spawned because by default the concurrency mode is set to “single”. When we set the concurrency mode to multiple in the callback behavior, it allows to spawn multiple threads to process these calls.
Note: Client application may spawn multiple threads to process the callbacks concurrently. If these callback methods access any shared resources, it may get into thread synchronization issues. So, it requires to ensure thread synchronization manually.
Hope this helps to save someone’s valuable time !
Pushpa Yadav (Microsoft)