I have implemented ClientBase to use WCF to connect to a service. I'm then calling a method on the channel to communicate with the service.
base.Channel.CalculateSomething();
Is this call thread safe or should I lock around it when running multiple threads?
Thanks
WCF does not create any queue for client messages and replays them as soon as they arrive. Each service has multiple threads processing messages concurrently. The service implementation must be thread-safe to use this concurrency mode.
the standard C printf() and scanf() functions use stdio so they are thread-safe.
A thread-safe routine is one that can be called concurrently from multiple threads without undesirable interactions between threads. A routine can be thread safe for either of the following reasons: It is inherently reentrant. It uses thread-specific data or lock on mutexes.
Thread safety is the technique which manipulates shared data structure in a manner that guarantees the safe execution of a piece of code by the multiple threads at the same time. A code is called thread-safe. If it is run concurrently without break function.
The follow-up comments on the answers here had me uncertain as well, so I did some more digging. Here is some solid evidence that ClientBase<T>
is thread-safe - this blog post discusses how to make a WCF service perform properly in the presence of a single client proxy being used by multiple threads simultaneously (the bold emphasis is in the original):
... However, there is a scenario where setting ConcurrencyMode to Multiple on a PerCall service can increase throughput to your service if the following conditions apply:
The client is multi-threaded and is making calls to your service from multiple threads using the same proxy.
The binding between the client and the service is a binding that has session (for example, netTcpBinding, wsHttpBinding w/Reliable Session, netNamedPipeBinding, etc.).
Also, the evidence in this post seems to contradict Brian's additional remark that WCF serializes any multi-threaded requests. The post shows multiple requests from a single client running simultaneously - if ConcurrencyMode.Multiple
and InstanceContextMode.PerCall
are used.
There is some additional discussion here regarding the performance implications of this approach as well as some alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With