Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to implement the following functionality in C# console application:

  1. spawn several worker threads in main thread;
  2. each worker thread processes data and send string message to main thread periodically;
  3. main thread processes messages and wait for all worker threads to finish;
  4. 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!

like image 412
xiagao1982 Avatar asked Nov 03 '25 10:11

xiagao1982


1 Answers

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.

like image 60
Mitch Avatar answered Nov 06 '25 02:11

Mitch