IAsyncDisposable.DisposeAsync 方法


以异步方式执行与释放或重置非托管资源相关的应用程序定义的任务。Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

 System::Threading::Tasks::ValueTask DisposeAsync();
public System.Threading.Tasks.ValueTask DisposeAsync ();
abstract member DisposeAsync : unit -> System.Threading.Tasks.ValueTask
Public Function DisposeAsync () As ValueTask


一个表示异步释放操作的任务。A task that represents the asynchronous dispose operation.


使用此方法异步关闭或释放由实现该接口的类的实例所持有的非托管资源,如文件、流和句柄。Use this method to asynchronously close or release unmanaged resources such as files, streams, and handles held by an instance of the class that implements this interface. 使用此方法而不是 IDisposable.Dispose 使你能够在不会长时间地阻止 GUI 应用程序的主线程的情况下执行占用大量资源的释放操作。Using this method instead of IDisposable.Dispose enables you to perform a resource-intensive dispose operation without blocking the main thread of a GUI application for a long time.


如果使用的是实现 IAsyncDisposable 接口的类,则应在使用完类后调用其 DisposeAsync 实现。If you are using a class that implements the IAsyncDisposable interface, you should call its DisposeAsync implementation when you are finished using the class. 有关详细信息,请参阅 IAsyncDisposable 主题中的 "使用实现 IAsyncDisposable 的对象" 一节。For more information, see the "Using an object that implements IAsyncDisposable" section in the IAsyncDisposable topic.

实现此方法时,请确保通过包含层次结构传播调用来释放所有保存的资源。When implementing this method, ensure that all held resources are freed by propagating the call through the containment hierarchy. 例如,如果对象 A 分配一个对象 B,并且对象 B 分配一个对象 C,则的 DisposeAsync 实现必须调用 B 上的 DisposeAsync,后者必须依次调用 C 上的 DisposeAsync。如果基类实现 IAsyncDisposable,则对象还必须调用其基类的 DisposeAsync 方法。For example, if an object A allocates an object B, and object B allocates an object C, then A's DisposeAsync implementation must call DisposeAsync on B, which must in turn call DisposeAsync on C. An object must also call the DisposeAsync method of its base class if the base class implements IAsyncDisposable.

如果多次调用某个对象的 DisposeAsync 方法,则该对象必须忽略第一个调用之后的所有调用,并以同步方式返回已成功完成的 ValueTaskIf an object's DisposeAsync method is called more than once, the object must ignore all calls after the first one and synchronously return a successfully completed ValueTask. 如果对象的 DisposeAsync 方法被多次调用,则该对象不得引发异常。The object must not throw an exception if its DisposeAsync method is called multiple times. 当资源已被释放时,DisposeAsync 的实例方法可能会引发 ObjectDisposedExceptionInstance methods other than DisposeAsync can throw an ObjectDisposedException when resources are already disposed.