Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

c# - async/await - Is this understanding correct?

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

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

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...