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能夠異步化是一個非常好的功能,畢竟它的作用就是用來釋放非託管資源,也能看到以後的大趨勢就是代碼異步化,函數化😄😄😄

本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章