简体   繁体   中英

async/await mechanism in C#

I have 2 questions that I would like to ask.

  1. I've read this paragraph in Microsoft documents about async/await. But I did not understand it clearly.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model#BKMK_APIAsyncMethods

"If GetStringAsync (and therefore getStringTask) completes before AccessTheWebAsync awaits it, control remains in AccessTheWebAsync. The expense of suspending and then returning to AccessTheWebAsync would be wasted if the called asynchronous process (getStringTask) has already completed and AccessTheWebSync doesn't have to wait for the final result."

Could you please explain it?

  1. As I read, when you use async/await in C#, the code is not running in two separate threads. It still in synchronous context, but it'll return Task in the case it meets "await" keyword as a promise that result will be returned until it completed. If the task completes before "await", it's now the same with synchronous. No differences. Even it's costly to switch from the caller method to "AccessTheWebAsync" method and vice versa.

Sorry, this is the first time I ask questions on StackOverflow.

An async method in C# must always return a Task and looks like this:

public async Task method();
public async Task<bool> asyncMethod();

When it doesn't return anything, so void just return Task and in any other case Task<returntype>

When you call upon an async method, you can do either 3 things:

// Result is now of type Task<object> and will run async with any code beyond this line.
// So using result in the code might result in it still being null or false.
var result = asyncMethod();

// Result is now type object, and any code below this line will wait for this to be executed.
// However the method that contains this code, must now also be async.
var result = await asyncMethod();

// Result is now type Task<object>, but result is bool, any code below this line will wait.
// The method with this code does not require to be async.
var result = asyncMethod().Result;

So to answer your questions.

Consider whether the result of the executed code is used elsewhere in the code, because if you don't await it, the result will be wasted, since it will still be null.

Same goes the other way around, when awaiting a method that won't return anything, then awaiting is usually not necessary.

Given the function:

async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    using (HttpClient client = new HttpClient())  
    {  
        Task<string> getStringTask = client.GetStringAsync("https://docs.microsoft.com");  

        DoIndependentWork();  

        string urlContents = await getStringTask;  

        return urlContents.Length;  
    }  
}   

When execution gets to

string urlContents = await getStringTask; 

the execution can do one of 2 things:

  1. If GetStringAsync() has already completed, the execution continues with the next line (return urlContents.Length; )
  2. If GetStringAsync() has not completed, then execution of AccessTheWebAsync() is suspended and execution returns to the calling function until GetStringAsync() completes. The paragraph your asking about is stating that If we suspended the execution of AccessTheWebAsync() anyway, the expense of suspending and then returning to AccessTheWebAsync would be wasted. Therefor this doesn't happen, as it is smart enough to know when to suspend execution and when not to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM