使用异步而不等待 [英] Using async without await

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

问题描述

我想让一个函数异步,所以我只需像这样添加 async :

I'd like to make a function async, so I simply add async like this:

public async static void something(){
}

你可以看到它的返回类型是void.我只想异步调用这个函数而不阻塞,因为返回是 void 所以不需要 await.

You can see that its return-type is void. I just want this function to be called asynchronously without blocking, since return is void so no await is needed.

但是 Visual Studio 2012 无法编译这个,它说我想念 await?

But Visual Studio 2012 just cannot compile this, it says that I miss await?

您能否提供一个示例,该示例使函数 async 不使用 await.

Could you please advise a sample that makes a function async without using await.

推荐答案

我想你可能误解了 async 的作用.警告是完全正确的:如果您将方法标记为 async 但不在任何地方使用 await,那么您的方法不会是异步的.如果调用它,方法内部的所有代码都会同步执行.

I think that maybe you misunderstand what async does. The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.

此外,您应该尽量避免使用 async void 方法,它们会使处理异常变得困难.

Also, you should try to avoid using async void methods, they make handling exceptions difficult.

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

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