Await 运算符只能在 Async 方法中使用 [英] Await operator can only be used within an Async method

查看:66
本文介绍了Await 运算符只能在 Async 方法中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的程序来测试 Visual Studio 2012 中新的 .NET 异步功能.我通常使用 BackgroundWorkers 异步运行耗时的代码,但有时对于一个相对简单的(但昂贵)操作.新的 async 修饰符看起来很好用,但不幸的是我似乎无法进行简单的测试.

这是我在 C# 控制台应用程序中的代码:

static void Main(string[] args){字符串 MarsResponse = 等待 QueryRover();Console.WriteLine("正在等待来自火星的回应...");Console.WriteLine(MarsResponse);Console.Read();}公共静态异步任务查询漫游器(){等待 Task.Delay(5000);return "做得很好!";}

我查看了 MSDN 上的一些示例,在我看来,这段代码应该可以正常工作,但是我在包含await QueryRover();"的行上收到了构建错误我是疯了还是有什么可疑的事情发生了?

解决方案

您只能在 async 方法中使用 awaitMain 不能是 async.>

您必须使用自己的 async 兼容上下文,对 Main<中返回的 Task 调用 Wait/code> 方法,或者只是忽略返回的 Task 并阻止对 Read 的调用.请注意,Wait 会将所有异常包装在 AggregateException 中.

如果你想要一个好的介绍,请看我的async/await 介绍帖.

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.

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!";
}

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.

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.

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

这篇关于Await 运算符只能在 Async 方法中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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