Can I await on a Task that was created on a different thread? For example:
...
CurrentIteration = Execute(); // returns Task
await CurrentIteration;
...
And then, on another thread:
...
await CurrentIteration;
...
CurrentIteration = Execute(); // returns Task
await CurrentIteration;
On the first thread?
I tried this code:
public class Program
{
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
public static async Task MainAsync(string[] args)
{
var instance = new SomeClass();
var task = instance.Execute();
Console.WriteLine("thread 1 waiting...");
Task.Run(async () =>
{
Console.WriteLine("thread 2 started... waiting...");
await task;
Console.WriteLine("thread 2 ended!!!!!");
});
await task;
Console.WriteLine("thread 1 done!!");
Console.ReadKey();
}
}
public class SomeClass
{
public async Task Execute()
{
await Task.Delay(4000);
}
}
But it prints
thread 1 waiting...
thread 2 started... waiting...
then
thread 1 done!!
but never thread 2 ended!!!!!
. Why is that? How can I achieve that? Thanks!
You can await
on a task from multiple threads. You were actually really close to get that to work, as @Rob said, you just needed to await
the second thread.
consider this:
public static async Task MainAsync(string[] args)
{
var instance = new SomeClass();
var task = instance.Execute();
Console.WriteLine("thread 1 waiting...");
var secondTask = Task.Run(async () =>
{
Console.WriteLine("thread 2 started... waiting...");
await task;
Console.WriteLine("thread 2 ended!!!!!");
});
await task;
await secondTask;
Console.WriteLine("thread 1 done!!");
Console.ReadKey();
}
Add the wait on your second thread after you finish waiting for the task.
The reason you didn't see the indication is because the console got stuck on the ReadKey
method, and couldn't write anything until it's finished. If you would've pressed Enter, you can see the "thread 2 ended!!!!!" line for a second before the app closes.
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