Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Dispose await for all async methods?

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.

like image 532
Denis535 Avatar asked May 14 '19 21:05

Denis535


People also ask

How do you use async disposable?

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.

How do I implement the async dispose pattern with JSON?

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.

Should I use async-await all the way?

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.

What is the use of disposeasynccore in async?

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.


Video Answer


1 Answers

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()
like image 63
Paulo Morgado Avatar answered Oct 03 '22 21:10

Paulo Morgado