Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

After two questions and much confusion - I wonder if I finally got it right. This is my understanding:

async/await serves only one purpose - to allow code to be executed after an already asynchronous task is finished. e.g.

async Task CallerMethod()
{
     await AsyncMethod();
     AnotherMethod();
}

allows AnotherMethod to be executed after the asynchronous AsyncMethod is finished instead of immediately after AsyncMethod is started.

async/await NEVER makes anything asynchronous. It doesn't start a separate thread (unless the awaited method does that anyway, of course), etc.

Is my understanding (finally) correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

Though Stephen's answer is correct, I want to make sure that you've got a few additional points clear.

async/await NEVER makes anything asynchronous

It makes CallerMethod an asynchronous method. CallerMethod returns a Task which can itself be awaited, and CallerMethod returns that task before the work of CallerMethod is itself complete, so it is an asynchronous method.

It doesn't make AsyncMethod asynchronous; it was already asynchronous.

It doesn't start a separate thread

Right. This is a frequent source of confusion. Threads are a unit of concurrency, which is only one kind of asynchrony. An analogy usually helps. You can put the bread in the toaster, wait for it to get toasted, and then make the eggs. You can put the bread in the toaster, cook the eggs while the toast is toasting, and then deal with the toast after the eggs are done. Or you can hire two cooks, one to cook eggs and one to make toast. The first is synchronous processing. The second and third are asynchronous, but only the third is concurrent. Notice that the third solution is the most expensive; threads are workers and workers aren't cheap.

What makes an asynchronous method asynchronous is not that it is concurrent -- though it might be. What makes it asynchronous is that it gives you a mechanism that allows you to do something else while you're waiting for its work to complete. await is just a pleasant way to write "here's the code I want you to run after the task has completed successfully".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...