[en] Proxy thread safety (solved)

Topics: Technical Support
Oct 18, 2013 at 6:38 AM
Is proxy created by ZyanConnection.CreatyProxy thread safe? If it isn't what will be better for multi thread access: locking or creating more proxies for same component?
Coordinator
Oct 18, 2013 at 9:22 AM
Zyan's proxies are based on RealProxy class, which is not guaranteed to be thread-safe (see MSDN):
 
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
 
As for locking vs. multiple proxies, I would prefer multiple proxies.
You can create proxy per thread or even proxy per request (proxy creation is cheap).
It may consume a bit more memory, but it will definitely outperform lock-based approach.
Holding a lock while making remote call is bad because most of this time your proxy is simply waiting for reply travelling over slow network.

I wrote a little benchmark to demonstrate it, and here is the result (the less time the better):
 
Shared proxy with lock benchmark. Time elapsed: 13.22
Per thread proxies benchmark. Time elapsed: 5.05
Per request proxies benchmark. Time elapsed: 5.33
 
Here is the code for my benchmark: https://gist.github.com/yallie/7038238
Marked as answer by zii_dmg on 10/18/2013 at 2:35 AM
Coordinator
Oct 18, 2013 at 8:31 PM
Edited Oct 18, 2013 at 8:31 PM
As a footnote: I never noticed anything odd when using shared proxies from multiple concurrent threads. Once constructed, .NET transparent proxies are essentially read-only, that's why calling Invoke method from multiple threads is (most likely) safe. Parts of code added by Zyan are designed to be thread-safe (we found and fixed a couple of race conditions in previous releases).

So, if you brave enough, you may choose to try using single proxy in all your threads without any locking :)