Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

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

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

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

instead of this

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

What is the difference between using and await using?

How should I decide which one to use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...