在C#中的Action中调用异步代码

我正在从一些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中调用异步代码?看来我做不到。如果我无法通过另一种方法将代码块传递给实用程序方法来执行?看起来像什么?


慕盖茨4494581
浏览 328回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP