I have 2 questions that I would like to ask.
"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?
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:
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.