NET问答: using 和 await using 有什么不同?

咨询区

  • Justin Lessard

我注意到在某些情况下,visual studio 经常推荐我这么做。


await using var disposable = new Disposable();
// Do something

来替代下面的这种写法


using var disposable = new Disposable();
// Do something

请问 usingawait using 到底有什么不同 ?或者说在使用上该怎么抉择?

回答区

  • Community

  1. 典型的同步 using

通常能调用 Dispose() 方法是因为这个对象实现了 IDisposable 接口,比如下面这样。


using var disposable = new Disposable();
// Do Something...

大家应该都知道,它等价于


IDisposable disposable = new Disposable();
try
{
    // Do Something...
}
finally
{
    disposable.Dispose();
}

  1. 新的异步using

之所以能使用 await 是因为一个对象使用了 IAsyncDisposable 接口并实现了 DisposeAsync() 方法,比如下面这样。


await using var disposable = new AsyncDisposable();
// Do Something...

它等价于


IAsyncDisposable disposable = new AsyncDisposable();
try
{
   // Do Something...
}
finally
{
   await disposable.DisposeAsync();
}

这个 IAsyncDisposable 接口是在 .NET Core 3.0.NET Standard 2.1 中加入的,接口签名如下:


    //
    // Summary:
    //     Provides a mechanism for releasing unmanaged resources asynchronously.
    public interface IAsyncDisposable
    {
        //
        // Summary:
        //     Performs application-defined tasks associated with freeing, releasing, or resetting
        //     unmanaged resources asynchronously.
        //
        // Returns:
        //     A task that represents the asynchronous dispose operation.
        ValueTask DisposeAsync();
    }

点评区

Dispose能够异步化是一个非常好的功能,毕竟它的作用就是用来释放非托管资源,也能看到以后的大趋势就是代码异步化,函数化????????????

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值