为什么 C# 4.5 async/await WebClient 在使用 StreamReader ReadToEndAsync 时需要 lambda 方法?
Why does C# 4.5 async/await WebClient require lambda methodology when using StreamReader ReadToEndAsync?
鉴于:
public async Task<string> SendRequest(this string url)
{
var wc = new WebClient();
wc.DownloadDataCompleted += (s, e) =>
{
var buffer = e.Result;
using (var sr = new StreamReader(new MemoryStream(buffer)))
{
var result = await sr.ReadToEndAsync();
};
};
wc.DownloadDataAsync(new Uri(url));
}
}
声明:
var result = await sr.ReadToEndAsync();
在设计器中显示错误如下:"The await operator can only be used within an async lambda expression"
我不明白为什么会出现此消息,当我查看所有 ReadToEndAsync 示例时,它们看起来与此代码完全一样。
请指教...
public static Task<string> SendRequest(this string url)
{
return (new WebClient()).DownloadStringTaskAsync(new Uri(url));
}
当使用带有 TPL 的 WebClient 时,您应该使用名称中带有 Task
的方法,以获得 Task
返回方法,而不是使用基于事件的模式(您随后将需要转化为任务):
public static async Task<string> SendRequest(this string url)
{
using (var wc = new WebClient())
{
var bytes = await wc.DownloadDataTaskAsync(url);
using (var reader = new StreamReader(new MemoryStream(bytes)))
return await reader.ReadToEndAsync();
}
}
鉴于:
public async Task<string> SendRequest(this string url)
{
var wc = new WebClient();
wc.DownloadDataCompleted += (s, e) =>
{
var buffer = e.Result;
using (var sr = new StreamReader(new MemoryStream(buffer)))
{
var result = await sr.ReadToEndAsync();
};
};
wc.DownloadDataAsync(new Uri(url));
}
}
声明:
var result = await sr.ReadToEndAsync();
在设计器中显示错误如下:"The await operator can only be used within an async lambda expression"
我不明白为什么会出现此消息,当我查看所有 ReadToEndAsync 示例时,它们看起来与此代码完全一样。
请指教...
public static Task<string> SendRequest(this string url)
{
return (new WebClient()).DownloadStringTaskAsync(new Uri(url));
}
当使用带有 TPL 的 WebClient 时,您应该使用名称中带有 Task
的方法,以获得 Task
返回方法,而不是使用基于事件的模式(您随后将需要转化为任务):
public static async Task<string> SendRequest(this string url)
{
using (var wc = new WebClient())
{
var bytes = await wc.DownloadDataTaskAsync(url);
using (var reader = new StreamReader(new MemoryStream(bytes)))
return await reader.ReadToEndAsync();
}
}