我正在使用async
框架进行网络通话。我在下面的代码中看到了错误
class Program
{
static void Main(string[] args)
{
TestAsync async = new TestAsync();
await async.Go();//Error: the await operator can only be used with an async method. Consider markign this method with the async modifier. Consider applying the await operator to the result of the call
}
}
class TestAsync
{
public async Task Go()
{
using (WebClient client = new WebClient())
{
var myString = await client.DownloadStringTaskAsync("http://msdn.microsoft.com");
Console.WriteLine(myString);
}
}
}
我尝试过这段代码的几种变体。它要么在运行时失败,要么不编译。在这种情况下,该方法在允许触发异步调用之前完成。我做错了什么?
我的目标是以异步方式使用WebClient执行对网站的调用。我想将结果作为字符串返回并使用Console.WriteLine
将其打印出来。如果您觉得从更简单的执行代码开始感觉更舒服
await async.Go();
到async.Go();
代码将会运行,但Console.WriteLine不会被命中。
答案 0 :(得分:2)
错误消息正确地告诉您await
只能在async
方法中使用。但是,您无法Main()
async
,C#也不支持。
但async
方法返回Task
s,与.Net 4.0中的TPL相同Task
。并且Task
确实支持使用the Wait()
method进行同步等待。所以,你可以像这样写代码:
class Program
{
static void Main(string[] args)
{
TestAsync async = new TestAsync();
async.Go().Wait();
}
}
使用Wait()
是正确的解决方案,但在其他情况下,使用Wait()
混合同步等待和使用await
进行异步等待可能会很危险并且可能导致死锁(尤其是在GUI中)应用程序或ASP.NET)。
答案 1 :(得分:-1)
程序在Web请求完成之前结束。这是因为Main不会等待异步操作完成,因为它没有什么可做的。
我敢打赌,如果你让Main持续时间更长,那么Console.WriteLine
将被调用。
我会尝试在调用异步方法后添加一个睡眠 - Thread.Sleep(500)
- 任何足够长的时间来允许Web请求完成都应该有效。