I'm running the following code (C#7.1 Console App), and I can't really understand why the difference in behavior.
If I await a regular async method call, or a Task.Run - it works as expected (i.e. the app doesn't return immediately). But if I use Task.Factory.StartNew - it will return immediately without the code actually running.
Strangely enough - if I use StartNew but inside the method remove the await, it will not return immediately...
Problem: This returns immediately:
static async Task Main(string[] args)
{
await Task.Factory.StartNew(DisplayCurrentInfo);
}
static async Task DisplayCurrentInfo()
{
await WaitAndApologize();
Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}");
Thread.Sleep(3000);
}
i.e. - I won't get to see anything printed out to the console, and the console will already be shut down.
No problem: this doesn’t return immediately:
static async Task Main(string[] args)
{
await DisplayCurrentInfo(); // or await Task.Run(DisplayCurrentInfo);
}
static async Task DisplayCurrentInfo()
{
await WaitAndApologize();
Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}");
Thread.Sleep(3000);
}
Strange: this also doesn't return immediately:
static async Task Main(string[] args)
{
await Task.Factory.StartNew(DisplayCurrentInfo);
}
static async Task DisplayCurrentInfo()
{
WaitAndApologize();
Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}");
Thread.Sleep(3000);
}
WaitAndApologize:
static async Task WaitAndApologize()
{
// Task.Delay is a placeholder for actual work.
await Task.Delay(2000);
// Task.Delay delays the following line by two seconds.
Console.WriteLine("\nSorry for the delay. . . .\n");
}