问题描述
我有一个带有异步方法的一次性类.
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等待所有异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!