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; ... - Will the second thread wait for method Execute to finish executing?
- If it will, will I be able to re-use CurrentIteration for the same purpose in the second thread, given that I re-run
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!
thread 1 done, sometimes it won't.awaitbeforeTask.Run...?await Task.Run, I would be waiting for it.