I have disposable class with async methods.
class Gateway : IDisposable {
public Gateway() {}
public void Dispose() {}
public async Task<Data> Request1 () {...}
public async Task<Data> Request2 () {...}
public async Task<Data> Request3 () {...}
}
I need Dispose to await until all running requests are completed.
So, either I need to track of all running tasks, or use AsyncLock
from AsyncEx, or something else?
Updated
As I can see someone is afraid of blocking Dispose. Then we could make Task WaitForCompletionAsync()
or Task CancelAllAsync()
methods.
Using async disposable To properly consume an object that implements the IAsyncDisposable interface, you use the await and using keywords together. Consider the following example, where the ExampleAsyncDisposable class is instantiated and then wrapped in an await using statement.
If you implement the async dispose pattern for any potential base class, you must provide the protected virtual ValueTask DisposeAsyncCore () method. Here is an example implementation of the async dispose pattern that uses a System.Text.Json.Utf8JsonWriter. The preceding example uses the Utf8JsonWriter.
The recommended approach is to go "async all the way" and use await. There is great reading material inside the async-await tag wiki, make sure to check it out. The both examples has issues. The first, in the thread case, the Dispose method is calling before the thread has ended.
It encapsulates the common asynchronous cleanup operations when a subclass inherits a base class that is an implementation of IAsyncDisposable. The DisposeAsyncCore () method is virtual so that derived classes can define additional cleanup in their overrides.
For the time being, you'll have to add a CloseAsync
method that your users have to invoke.
Once C# 8.0 is released, you can rely on the IAsyncDisposable
Interface and its language support:
await using (var asyncDisposable = GetAsyncDisposable())
{
// ...
} // await asyncDisposable.DisposeAsync()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With