在 C# 中使用语句和等待关键字效果很好 [英] Do using statements and await keywords play nicely in c#

查看:23
本文介绍了在 C# 中使用语句和等待关键字效果很好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我正在对返回和 IDisposable 实例的方法进行 async 调用.例如:

I have a situation where I am making an async call to a method that returns and IDisposable instance. For example:

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

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

Now before async was on the scene, when working with an IDisposable instance, this call and code that used the "response" variable would be wrapped in a using statement.

我的问题是,当 async 关键字被混合使用时,这是否仍然是正确的方法?即使代码编译通过, using 语句在下面的两个示例中仍能按预期工作吗?

My question is whether that is still the correct approach when the async keyword is thrown in the mix? Even though the code compiles, will the using statement still work as expected in both the examples below?

示例 1

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;
}

推荐答案

是的,应该没问题.

在第一种情况下,您实际上是在说:

In the first case, you're really saying:

  • 异步等待,直到我们可以得到响应
  • 使用它并立即处理它

在第二种情况下,您是说:

In the second case, you're saying:

  • 异步等待,直到我们可以得到响应
  • 异步等待,直到我们记录了响应
  • 处理响应

异步方法中的 using 语句是奇怪的",因为 Dispose 调用可能在与获取资源的线程不同的线程中执行(取决于同步上下文等)但它仍然会发生......当然,假设你正在等待的事情永远出现或失败.(就像如果您的 using 语句包含对永不返回的方法的调用,您最终不会在非异步代码中调用 Dispose 一样.)

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.)

这篇关于在 C# 中使用语句和等待关键字效果很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆