等待操作者只能异步方法中使用 [英] Await operator can only be used within an Async method

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

问题描述

我试图做一个简单的程序到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.

如果你想有一个很好的介绍,请参阅我的<一个href="http://blog.stephencleary.com/2012/02/async-and-await.html"><$c$c>async/<$c$c>await开场后。

If you want a good intro, see my async/await intro post.

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

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