异步一次性创建 [英] Async Disposable.Create
问题描述
Disposable.Create 需要Action
作为参数. Action
在处理Rx订阅时运行.
Disposable.Create require an Action
as parameter. The Action
is run when the Rx subscription is being disposed.
在处置Rx订阅时,我想运行一些异步清理代码,但是将async () =>
与Action
结合使用与async void
相同,我想避免这种情况.有关为什么要避免这种情况的更多详细信息,请参见此处.
When disposing a Rx subscription I’d like to run some asynchronous clean up code, however using async () =>
with Action
is identical to async void
, which I’d like to avoid. For more details on why I want to avoid this, see here.
是否可以创建类似Disposable.AsyncCreate
的内容,该内容接受Func<Task>
而不是Action
.如果是这样,我应该如何将其用作CompositeDisposable
的一部分?
Is it possible to create something like a Disposable.AsyncCreate
, which accepts Func<Task>
rather than Action
. If so how should I use it as part of a CompositeDisposable
?
或者还有其他处理异步处理的模式吗?
Or are there other patterns for dealing with asynchronous Disposal?
推荐答案
您可以执行以下操作.我仍然不确定这是一个好主意:
You could do something like this. I'm still not sure how good an idea it is:
public class DisposableAsync
{
private readonly IDisposable _disposable;
private readonly Func<Task> _asyncDisposalAction;
public DisposableAsync(IDisposable disposable, Func<Task> asyncDisposalAction)
{
_disposable = disposable;
_asyncDisposalAction = asyncDisposalAction;
}
public Task DisposeAsync()
{
_disposable.Dispose();
return _asyncDisposalAction();
}
}
public static class DisposableAsyncExtensions
{
public static DisposableAsync ToAsync(this IDisposable disposable, Func<Task> asyncDisposalAction)
{
return new DisposableAsync(disposable, asyncDisposalAction);
}
}
然后您可以像这样使用它:
You could then use it like this:
async Task Go()
{
var o = Observable.Interval(TimeSpan.FromMilliseconds(100));
var d = o
.Subscribe(i => Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: {i}"))
.ToAsync(async () =>
{
Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Dispose Beginning");
await Task.Delay(1000);
Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Dispose Complete");
});
Console.Read();
var t = d.DisposeAsync();
Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Outside task, waiting for dispose to complete");
await t;
Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Task Complete");
}
此解决方案不适用于using()
语句,并且应该增强类DisposableAsync
.除此之外,我想不出什么错,但是我对此很反对.只是有点.
This solution wouldn't work with using()
statements, and the class DisposableAsync
should be robustified. Outside of that, I can't think of anything wrong with it, but I'm predisposed (ahem) against it though. Just feels kind of hacky.
这篇关于异步一次性创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!