I want to implement the following functionality in C# console application:
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With