The problem is not well-defined. The notion of "return an object" and "output" in its traditional sense has little in common. It output means simply getting some data produced by a worker thread, the question is "at what moment of time", that is, a synchronization.
Let's start from a simple model: a worker thread puts some data in a shared memory and another thread reads the latest value. Sometimes it is needed. The simple answer is using
lock
statement on the same object. Very often several threads mostly read, some threads write, less often. In this case a special kind of mutex or lock helps to improve performance:
System.Threading.ReaderWriterLockSlim
. You get this lock for read first, and if write is required, "upgrade" it for writing.
One of my articles illustrates the great benefit of this class:
Wish You Were Here… Only Once[
^] with code samples.
If you think you know a good way of thread input, perhaps you need to think again. Please look at the code of thread wrapper:
How to pass ref parameter to the thread[
^].
Now, let's get back to thread "output". A really robust way is thread communication in
producer-consumer manner. This can be achieved using
System.Threading.EventWaitHandle
. Please see my generic blocking queue which can be used for this purpose. It can even be used for inter-thread method invocation. See my Tips/Tricks article on the topic:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^].
You will find completed source code and detailed usage samples.
Good luck,
—SA