【发布时间】:2012-08-17 05:26:09
【问题描述】:
我正在使用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。
【问题讨论】:
-
在
Main()中直接使用 await 没有任何意义。你希望它做什么? -
我想异步执行网络调用。该函数是任意的,我只想设置一个基本的异步调用来学习语法的基础知识。随意以任何您认为合适的方式拨打网络电话。
-
在 .net 中学习异步的好资源:msdn.microsoft.com/en-us/vstudio/hh378091
-
顺便说一句,
using对于WebClient是不必要的。大多数时候,你应该确保你Dispose()任何实现IDisposable的东西,但WebClient拥有它只是因为它的基础 (Component) 有。
标签: c# visual-studio-2012 c#-5.0