Here is the code:
static async Task Main(string[] args)
{
var t = new Task(async () => await AsyncTest());
t.Start();
t.Wait();
Console.WriteLine("Main finished");
}
private static async Task AsyncTest()
{
Thread.Sleep(2000);
await Task.Delay(2000);
Console.WriteLine("Method finished");
}
My expectation is that t.Wait()
will actually wait for AsyncTest
method completion and output will be:
Method finished
Main finished
In reality output has only Main finished
. Wait() is completed right at the moment when you hit await Task.Delay(2000)
inside AsyncTest. The same happens if you replace t.Wait()
with await t
/ await Task.WhenAll(t)
/ Task.WaitAll(t)
.
The solution is to rewrite method to synchronous implementation or call Wait() directly on AsyncTest(). However, the question is why does it work in such strange way?
P.S. It's a simplified version of code. I was trying to achieve deferred task execution. In reality Task object is created by one part of program and then later is executed by another part after some specific condition.
UPD: Rewriting var t = new Task(async () => await AsyncTest())
to var t = new Task(()=> AsyncTest().Wait())
also fixes the problem. Though I still don't quite understand why Task doesn't work correctly with async/await inside delegate.