using和await using有什么不同?

咨询区

  • Justin Lessard

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

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

来替代下面的这种写法

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

请问 using 和 await 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能够异步化是一个非常好的功能,毕竟它的作用就是用来释放非托管资源,也能看到以后的大趋势就是代码异步化,函数化。