I want to implement the following functionality in C# console application:
- spawn several worker threads in main thread;
- each worker thread processes data and send string message to main thread periodically;
- main thread processes messages and wait for all worker threads to finish;
- main thread exit.
Now I’m using TPL, but I don’t know how to send messages from worker threads to main thread. Thank you for help!
You could use a Producer / Consumer pattern with the TPL as demonstrated in this example on an MSDN blog.
Or, you could kick it old-school and use signaling, see
AutoResetEvent.Or if you care to work at a very low level, use
Monitor.PulsewithMonitor.WaitOne(as demonstrated here).Either way, you are looking for Synchronization, which you can read up on here.
Other option, if you don’t actually care what thread the update is running on, would be to take a delegate as an argument and print the update there, à la:
would print:
The
"update message"call toConsole.WriteLinewould still occur on theThreadPoolthread, but it may still fill your need.