随时都可能接到需要进行长时间操作的方法调用。
这些方法有几个。因为它们共享一个资源,所以重要的是它们不应该同时运行 - 每个方法应该按顺序运行。
通常情况下,我会按顺序依次进行调用:
var result1 = await Foo1Async();
var result2 = await Foo2Async();
然而,在这种情况下,我的方法调用是异步的:
void Bar1()
{
var result = await Foo1Async();
// ...
}
void Bar2()
{
var result = await Foo2Async();
// ...
}
我认为我需要使用Task.ContinueWith
,并想出了以下代码:
readonly object syncLock = new Object();
private Task currentOperationTask = TaskUtilities.CompletedTask;
public Task<TResult> EnqueueOperation<TResult>(Func<Task<TResult>> continuationFunction)
{
lock (this.syncLock)
{
var operation = this.currentOperationTask.ContinueWith(predecessor => continuationFunction()).Unwrap();
this.currentOperationTask = operation;
return operation;
}
}
我是这样使用它的:
void Bar1()
{
var result = await EnqueueOperation(() => Foo1Async());
// ...
}
void Bar2()
{
var result = await EnqueueOperation(() => Foo2Async());
// ...
}
这是正确的解决问题的方法吗?有什么我需要注意的陷阱吗?
(Task<TResult> continuationFunction)
,你可以省略() =>
。 - SimpleVarawait EnqueueOperation(Foo1Async);
(不需要 lambda)。 - svick