I’m new to both WCF and threading, so please bear with me. I have a WCF service set up. The service has multiple threads, all of which act upon a single array. This works without a problem so far. However, this service has a method, which, when called, will return the array. My questions:
-
The array is serialized when it is transferred to the client by WCF. Is this a thread safe operation? In other words, can I count on WCF to block all threads from accessing this array while it’s being serialized?
-
If I can’t count on WCF to do this, then how can I implement it manually? I don’t really understand how WCF would facilitate this since the serialization happens after I return from my method call. How can I guarantee a thread will not modify the array after it’s been returned by my method but before WCF serializes it?
No, the WCF runtime won’t lock the data for you. Even if it would, it can’t keep you of from accessing the array in another thread.
I think the only possibilty to get this threadsafe is to copy the data you return in a private variable before leaving the function:
EDIT
If its not an option to copy large datastructures another option might be to not return an array but an instance of a custom class which implements
ISerializable.That way you can write a threadsafe serialization of your data yourself.
But before doing that, i would measure the impact of the extra copy.