C# Await 运算符只能在 Async 方法中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11836325/
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
Await operator can only be used within an Async method
提问by William Thomas
I'm trying to make a simple program to test the new .NET async functionality within Visual Studio 2012. I generally use BackgroundWorkers to run time-consuming code asynchronously, but sometimes it seems like a hassle for a relatively simple (but expensive) operation. The new async modifier looks like it would be great to use, but unfortunately I just can't seem to get a simple test going.
我正在尝试制作一个简单的程序来测试 Visual Studio 2012 中新的 .NET 异步功能。我通常使用 BackgroundWorkers 异步运行耗时的代码,但有时对于相对简单(但昂贵)的操作来说似乎很麻烦. 新的 async 修饰符看起来很好用,但不幸的是我似乎无法进行简单的测试。
Here's my code, in a C# console application:
这是我的代码,在 C# 控制台应用程序中:
static void Main(string[] args)
{
string MarsResponse = await QueryRover();
Console.WriteLine("Waiting for response from Mars...");
Console.WriteLine(MarsResponse);
Console.Read();
}
public static async Task<string> QueryRover()
{
await Task.Delay(5000);
return "Doin' good!";
}
I checked out some examples on MSDN and it looks to me like this code should be working, but instead I'm getting a build error on the line containing "await QueryRover();" Am I going crazy or is something fishy happening?
我查看了 MSDN 上的一些示例,在我看来,这段代码应该可以正常工作,但是我在包含“await QueryRover();”的行上收到了一个构建错误。我是疯了还是有什么可疑的事情发生了?
采纳答案by Stephen Cleary
You can only use awaitin an asyncmethod, and Maincannot be async.
您只能await在async方法中使用,Main不能在async.
You'll have to use your own async-compatible context, call Waiton the returned Taskin the Mainmethod, or just ignore the returned Taskand just block on the call to Read. Note that Waitwill wrap any exceptions in an AggregateException.
您必须使用您自己的async兼容上下文,调用方法中Wait返回Task的Main,或者只是忽略返回的Task并阻塞对 的调用Read。请注意,Wait会将任何异常包装在AggregateException.
If you want a good intro, see my async/awaitintro post.
如果您想要一个好的介绍,请参阅我的async/await介绍帖子。

