如何使Dispose等待所有异步方法

如何使Dispose等待所有异步方法

本文介绍了如何使Dispose等待所有异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有异步方法的一次性类.

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 () {...}
}

我需要Dispose等待所有正在运行的请求完成.

I need Dispose to await until all running requests are completed.

那么,我需要跟踪所有正在运行的任务,还是使用AsyncEx中的AsyncLock或其他功能?

So, either I need to track of all running tasks, or use AsyncLock from AsyncEx, or something else?

已更新

正如我所见,有人害怕阻止Dispose.然后我们可以制作Task WaitForCompletionAsync()Task CancelAllAsync()方法.

As I can see someone is afraid of blocking Dispose. Then we could make Task WaitForCompletionAsync() or Task CancelAllAsync() methods.

推荐答案

暂时,您必须添加用户必须调用的CloseAsync方法.

For the time being, you'll have to add a CloseAsync method that your users have to invoke.

一旦发布 C#8.0 ,您就可以依赖 IAsyncDisposable接口及其语言支持:

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()

这篇关于如何使Dispose等待所有异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:22