gpt4 book ai didi

c# - using 和 await using 有什么区别?我如何决定使用哪一个?

转载 作者:行者123 更新时间:2023-12-04 10:06:27 26 4
gpt4 key购买 nike

我注意到在某些情况下,Visual Studio 建议这样做

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

而不是这个
using var disposable = new Disposable();
// Do something
using有什么区别和 await using ?

我应该如何决定使用哪一个?

最佳答案

经典同步使用
经典使用电话 Dispose()实现 IDisposable 的对象的方法界面。

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

相当于
IDisposable disposable = new Disposable();
try
{
// Do Something...
}
finally
{
disposable.Dispose();
}
新的异步等待使用
新的 await 使用调用和 await DisposeAsync()实现 IAsyncDisposable 的对象的方法界面。
await using var disposable = new AsyncDisposable();
// Do Something...

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

IAsyncDisposable Interface已添加于 .NET Core 3.0.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.

关于c# - using 和 await using 有什么区别?我如何决定使用哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58610350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com