我从一些C#代码调用Web服务。此代码与此类似:
using (var client = new HttpClient())
{
var page = "http://en.wikipedia.org/";
using (var response = await client.GetAsync(page))
{
using (var content = response.Content)
{
var result = await content.ReadAsStringAsync();
}
}
}
我想在实用程序方法中执行此代码。根据我的理解,Action代表适合这一点。我尝试使用以下方法执行此操作:
Action action = delegate()
{
using (var client = new HttpClient())
{
var page = "http://en.wikipedia.org/";
using (var response = await client.GetAsync(page))
{
using (var content = response.Content)
{
var result = await content.ReadAsStringAsync();
}
}
}
}
当我将我的Web服务代码包装在Action
委托中时,我收到一个编译时错误,上面写着:
The 'await' operator can only be used within an async anonymous method. Consider marking this anonymous method with the 'async' modifier.
我的问题是,如何在Action中调用异步代码?看起来我不能。如果我不能用另一种方法将一段代码传递给实用程序方法执行?那是什么样的?
谢谢!
答案 0 :(得分:0)
您需要将行为标记为async
,就像使用任何方法一样,例如:
Action action = async delegate()
//snip
但是,这相当于async
void
方法,不建议这样做。相反,您可以考虑使用Func<Task>
代替操作:
Func<Task> doStuff = async delegate()
{
using (var client = new HttpClient())
{
var page = "http://en.wikipedia.org/";
using (var response = await client.GetAsync(page))
{
using (var content = response.Content)
{
var result = await content.ReadAsStringAsync();
}
}
}
}
现在你可以等待结果:
await doStuff();