简体   繁体   中英

Why is it necessary for async method to have await

We use async keyword to make a method asynchronous. If the method does not use any await keyword, then the compiler generates the warning that the method will run synchronously. But I do not understand why this is so. Let us assume that method f() calls method g() and f does not need to wait for g to complete. This means f needs to call g asynchronously. But such a requirement may arise even if g does not need to use any await. How will this be achieved?

Let us assume that method f() calls method g() and f does not need to wait for g to complete.

Are you sure? "Fire and forget" literally means forget . Ie, you seriously don't care at all if g never completes, and you're OK with all exceptions from g being silently swallowed. That's what "fire and forget" actually means, and >90% of the time it's not what people really want.

This means f needs to call g asynchronously.

And the way it does so is via await :

async Task f() => await g();

For your purpose you can use Task.Run or Task.Factory.Start to fire and forget your method g :

void f() {
    ...
    Task.Run(() => g())
    ...
}

When calling an async method that doesn't apply the await operator it starts as asynchronous task. As no await operators are applied inside this method, the program continues without waiting for the task to complete. (see Compiler Warning (level 1) CS4014 )

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