What is the difference between using and await using? And how can I decide which one to use?

后端 未结 1 1494
长发绾君心
长发绾君心 2020-12-01 17:51

I\'ve noticed that in some case, Visual Studio recommends to do this

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

instead

相关标签:
1条回答
  • 2020-12-01 18:11

    Classic sync using

    Classic using calls the Dispose() method of an object implementing the IDisposable interface.

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

    Is equivalent to

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

    New async await using

    The new await using calls and await the DisposeAsync() method of an object implementing the IAsyncDisposable interface.

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

    Is equivalent to

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

    The IAsyncDisposable Interface was added in .NET Core 3.0 and .NET Standard 2.1.

    In .NET, classes that own unmanaged resources usually implement the IDisposable interface to provide a mechanism for releasing unmanaged resources synchronously. However, in some cases they need to provide an asynchronous mechanism for releasing unmanaged resources in addition to (or instead of) the synchronous one. Providing such a mechanism enables the consumer to perform resource-intensive dispose operations without blocking the main thread of a GUI application for a long time.

    The IAsyncDisposable.DisposeAsync method of this interface returns a ValueTask that represents the asynchronous dispose operation. Classes that own unmanaged resources implement this method, and the consumer of these classes calls this method on an object when it is no longer needed.

    0 讨论(0)
提交回复
热议问题