为什么在必须使用等待时使用异步? [英] Why use async when I have to use await?

查看:97
本文介绍了为什么在必须使用等待时使用异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上停留了一段时间了,还没有真正找到关于这是为什么的有用解释。

I've been stuck on this question for a while and haven't really found any useful clarification as to why this is.

如果我有一个 async 这样的方法:

If I have an async method like:

public async Task<bool> MyMethod()
{
    // Some logic
    return true;
}

public async void MyMethod2()
{
    var status = MyMethod(); // Visual studio green lines this and recommends using await
}

如果我使用 await 在这里,异步方法的意义是什么?是不是让VS告诉我调用 await 来使 async 无效?

If I use await here, what's the point of the asynchronous method? Doesn't it make the async useless that VS is telling me to call await? Does that not defeat the purpose of offloading a task to a thread without waiting for it to finish?

推荐答案


如果我在这里使用await,异步方法的意义是什么?

If I use await here, what's the point of the asynchronous method?

await 不阻塞线程。 MyMethod2 将同步运行,直到达到 await 表达式为止。然后 MyMethod2 将被暂停,直到等待的任务( MyMethod )完成。当 MyMethod 未完成时,控制权将返回给 MyMethod2 的调用方。这就是等候的意义-呼叫者将继续做它的工作

await does not block thread. MyMethod2 will run synchronously until it reaches await expression. Then MyMethod2 will be suspended until awaited task (MyMethod) is complete. While MyMethod is not completed control will return to caller of MyMethod2. That's the point of await - caller will continue doing it's job.


VS让我叫await异步使它变得没用吗?

Doesn't it make the async useless that VS is telling me to call await?

async 只是一个标志,表示在方法中的某个地方您有一个或多个等待。

async is just a flag which means 'somewhere in the method you have one or more await'.


难道不辜负了将任务卸载到线程
而不等待任务完成的目的吗?

Does that not defeat the purpose of offloading a task to a thread without waiting for it to finish?

如上所述,您不必等待任务完成。

As described above, you don't have to wait for task to finish. Nothing is blocked here.

注意:要遵循框架命名标准,建议您将 Async 后缀添加到异步方法中名称。

NOTE: To follow framework naming standards I suggest you to add Async suffix to asynchronous method names.

这篇关于为什么在必须使用等待时使用异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆