Having created the following console application, I am a little puzzled why it works synchronously instead of asynchronously:
class Program { static void Main(string[] args) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var total = CreateMultipleTasks(); stopwatch.Stop(); Console.WriteLine("Total jobs done: {0} ms", total.Result); Console.WriteLine("Jobs done in: {0} ms", stopwatch.ElapsedMilliseconds); } static async Task<int> CreateMultipleTasks() { var task1 = WaitForMeAsync(5000); var task2 = WaitForMeAsync(3000); var task3 = WaitForMeAsync(4000); var val1 = await task1; var val2 = await task2; var val3 = await task3; return val1 + val2 + val3; } static Task<int> WaitForMeAsync(int ms) { Thread.Sleep(ms); return Task.FromResult(ms); } }
When the application starts, the output is:
Total Jobs Completed: 12,000 ms
Jobs done in: 12003 ms
I would expect something like:
Total Jobs Completed: 12,000 ms
Work done in: 5003 ms
Is this because when I use the Thread.Sleep method, does it stop further execution of the entire application? Or did I miss something important here?
source share