How to spawn worker threads and process their outputs in main thread in C#?

c#, multithreading, task-parallel-library

Solution

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.Pulse` with `Monitor.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:

static Task<string> ReadFile(string filename, Action<string> updateStatus)
{

    //do stuf synchronously
    return Task<string>.Factory.StartNew(() => {
        System.Threading.Thread.Sleep(1000);
        //do async stuff
        updateStatus("update message");
        //do other stuff
        return "The result";
    });
}

public static void Main(string[] args) 
{
    var getStringTask = ReadFile("File.txt", (update) => {
        Console.WriteLine(update)
    });
    Console.Writeline("Reading file...");
    //do other stuff here
    //getStringTask.Result will wait if not complete
    Console.WriteLine("File contents: {0}", getStringTask.Result);
}

would print:

Reading file...
update message
File contents: The result

The `"update message"` call to `Console.WriteLine` would still occur on the `ThreadPool` thread, but it may still fill your need.

Problem

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!

Original source