我正在使用async框架进行web调用。我在下面的代码中发现了一个错误
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(); to async.Go();代码将会运行,但不会命中Console.WriteLine。
发布于 2012-08-22 04:25:32
错误消息正确地告诉您,只能在async方法中使用await。但是,你不能让Main() async,C#不支持它。
但是async方法返回Tasks,这是自.Net 4.0以来在第三方公共语言中使用的同一个Task。并且Task支持使用the Wait() method的同步等待。因此,您可以像这样编写代码:
class Program
{
static void Main(string[] args)
{
TestAsync async = new TestAsync();
async.Go().Wait();
}
}这里使用Wait()是正确的解决方案,但在其他情况下,使用Wait()混合使用同步等待和使用await混合使用异步等待可能很危险,并且可能导致死锁(特别是在图形用户界面应用程序或ASP.NET中)。
发布于 2012-08-22 04:16:03
在web请求可以完成之前,程序即将结束。这是因为Main不会等待异步操作完成,因为它已无事可做。
我敢打赌,如果你让Main的持续时间更长,那么Console.WriteLine就会被调用。
我会尝试在调用async方法后添加一个休眠- Thread.Sleep(500) -任何足够长的时间来允许web请求完成应该都可以工作。
https://stackoverflow.com/questions/12062110
复制相似问题