Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is invoking a method on the same line as awaiting it considered asynchronous?

Tags:

c#

async-await

I'm looking at the examples on http://www.dotnetperls.com/async to better understand async/await, but the following is confusing to me:

I understand why the example below is considered asynchronous. HandleFileAsync is invoked, the Console.WriteLine call is made, then we await the completion of task before proceeding.

static async void ProcessDataAsync()
{
     // Start the HandleFile method.
     Task<int> task = HandleFileAsync("C:\\enable1.txt");

     // Control returns here before HandleFileAsync returns.
     // ... Prompt the user.
     Console.WriteLine("Please wait patiently " +
         "while I do something important.");

     // Wait for the HandleFile task to complete.
     // ... Display its results.
     int x = await task;
     Console.WriteLine("Count: " + x);
}

However in the following example, we await a call to Task.Run which runs an action:

static async void Example()
{
     // This method runs asynchronously.
     int t = await Task.Run(() => Allocate());
     Console.WriteLine("Compute: " + t);
}

So, if we are awaiting the completion of Task.Run here, what exactly is happening asynchronously? I thought it becomes a blocking call once as soon as we await the subsequent task's execution to complete, which, in this case is invoked on the same line.

What am I missing?

like image 577
bulletblue Avatar asked Jan 06 '23 01:01

bulletblue


1 Answers

I thought it becomes a blocking call once as soon as we await the subsequent task's execution to complete, which, in this case is invoked on the same line. What am I missing?

Your belief is false; that's what you're missing. "await" means "return now, go run something else while we are asynchronously waiting, and when the result is available, come back here."

Fetching the result of the task does what you think await does. We would not have had to invent await if all it did was synchronously fetch the result of the task! It asynchronously fetches the result of the task.

While we're at it, this comment is wrong:

// Control returns here before HandleFileAsync returns.

How could that possibly be? HandleFileAsync returned a task! How did control get to that point with a task in hand if HandleFileAsync did not return? Of course it returned.

And this comment is misleading:

// Wait for the HandleFile task to complete.

That should be asynchronously wait for the task to complete. By asynchronously waiting, remember, we mean "return now, go run more work, and when the task is complete, resume at this point with the result in hand."

I would find a better tutorial if I were you.

like image 187
Eric Lippert Avatar answered Jan 08 '23 15:01

Eric Lippert