使用语句和等待关键字在 c # 中可以很好地发挥作用

我遇到了这样一种情况: 我对返回的方法和 IDisposable实例进行 async调用。例如:

HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com"));

现在,在 async出现之前,当使用 IDisposable实例时,这个调用和使用“ response”变量的代码将包装在 using 语句中。

我的问题是,当 async关键字被混合在一起时,这是否仍然是正确的方法?即使代码已经编译,using 语句在下面的两个示例中是否仍然能够正常工作?

例子一

using(HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com")))
{
// Do something with the response


return true;
}

例子2

using(HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.google.com")))
{
await this.responseLogger.LogResponseAsync(response);


return true;
}
24178 次浏览

Yes, that should be fine.

In the first case, you're really saying:

  • Asynchronously wait until we can get the response
  • Use it and dispose of it immediately

In the second case, you're saying:

  • Asynchronously wait until we can get the response
  • Asynchronously wait until we've logged the response
  • Dispose of the response

A using statement in an async method is "odd" in that the Dispose call may execute in a different thread to the one which acquired the resource (depending on synchronization context etc) but it will still happen... assuming the thing you're waiting for ever shows up or fail, of course. (Just like you won't end up calling Dispose in non-async code if your using statement contains a call to a method which never returns.)