While trying to figure out the new (maybe not so new now, but new to me, anyway) Task asynchronous programming in C#, I ran into a problem that took me a bit to fig
The issue with your code is that there are two tasks at play. One is the result of your Task.Factory.StartNew call, which causes the anonymous function to be executed on the thread pool. However, your anonymous function is in turn compiled to produce a nested task, representing the completion of its asynchronous operations. When you wait on your Task, you're only waiting on the outer task. To wait on the inner task, you should use Task.Run instead of Task.Factory.StartNew, since it automatically unwraps your inner task:
Random rng = new Random((int)DateTime.UtcNow.Ticks);
int delay = rng.Next(1500, 15000);
Task testTask = Task.Run(
async () =>
{
DateTime startTime = DateTime.Now;
Console.WriteLine("{0} - Starting test task with delay of {1}ms.", DateTime.Now.ToString("h:mm:ss.ffff"), delay);
await Task.Delay(delay);
Console.WriteLine("{0} - Test task finished after {1}ms.", DateTime.Now.ToString("h:mm:ss.ffff"), (DateTime.Now - startTime).TotalMilliseconds);
return delay;
});
Task[] tasks = new[] { testTask };
Task.WaitAll(tasks);
Console.WriteLine("{0} - Finished waiting.", DateTime.Now.ToString("h:mm:ss.ffff"));
// make console stay open till user presses enter
Console.ReadLine();