.NET Inside Out Part 24 – Synchronous waiting for the Task in the same frame

This is the twentieth fourth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Let’s take this code:

and compare it with this one:

They look very similar, however, they give different outputs. First code runs both tasks (Handle and one sleeping) on the same thread:

while the latter runs on different threads:

Why? That’s because scheduler tries to detect a situation when we are waiting on the task immediately (first code) and run it inline. In the second code this cannot be detected as we wait for “different” task.