C# 使用异步而不等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12016567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:05:27  来源:igfitidea点击:

Using async without await

c#asynchronousvisual-studio-2012async-awaitc#-5.0

提问by Eric Yin

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

我想让一个函数异步,所以我简单地添加async如下:

public async static void something(){
}

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

可以看到它的返回类型是void. 我只是想这一功能,必须异步调用不会阻塞,因为回报void所以没有await需要。

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

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

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

您能否提供一个示例,该示例async无需使用await.

采纳答案by svick

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

我想也许你误解了什么async。警告是完全正确的:如果你标记你的方法async但不在await任何地方使用,那么你的方法不会是 asynchronous。如果调用它,该方法内的所有代码都会同步执行。

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

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