我有一个具有以下结构的方法:
public Task InitializeAsync()
{
var taskCompletionSource = new TaskCompletionSource<bool>();
Task firstTask = ...;
// secondTask calls taskCompletionSource.TrySetResult(true) once it considers itself "done"
Task secondTask = firstTask.ContinueWith(..., TaskContinuationOptions.OnlyOnRanToCompletion);
Action<TasK> errorContinuation = x =>
{
taskCompletionSource.SetException(e.Exception);
};
firstTask.ContinueWith(errorContinuation, TaskContinuationOptions.OnlyOnFaulted);
secondTask.ContinueWith(errorContinuation, TaskContinuationOptions.OnlyOnFaulted);
return taskCompletionSource.Task;
}
重要提示:
InitializeAsync
返回的任务直到secondTask
决定结束才算完成- 只有当
firstTask
成功时,secondTask
才会运行 - 无论是
firstTask
还是secondTask
失败都会导致整个任务失败
我在想是否有更简洁、更简单的方式来表达这个功能。我正在使用 .NET 4.0,但也想知道 4.5 是否能使此过程更加容易。