我试图做一个简单的程序到Visual Studio 2012年。我一般用BackgroundWorkers运行中测试新的.NET异步功能耗时code异步方式,但有时它似乎是一个麻烦的比较操作简单(但价格昂贵)。新的异步修饰符看起来这将是伟大的使用,但不幸的是我似乎无法得到一个简单的测试准备。
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.
下面是我的code,在C#控制台应用程序:
Here's my code, in a C# console application:
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!";
}
我检查了MSDN上的一些例子,它看起来对我来说,这个code应该是工作,而是我对包含该行收到生成错误等待QueryRover();我是不是疯了还是有鬼发生?
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?
您只能使用等待
在异步
方法,和 主
不能异步
。
You can only use await
in an async
method, and Main
cannot be async
.
您将不得不使用自己的异步
兼容的情况下,调用等待
在返回工作
在主
的方法,或者忽略返回工作
和公正阻塞调用读
。需要注意的是等待
将包装中的任何异常的 AggregateException
。
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
如果你想有一个很好的介绍,请参阅我的async/await开场后。
If you want a good intro, see my async
/await
intro post.