處理我有以下結構的方法:任務組成和誤差TPL
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決定這樣 secondTask
僅當firstTask
成功時才運行- 任一故障
firstTask
或secondTask
導致整個任務失敗
什麼我不知道是是否有一個更清潔,更簡單的表達,一面實現相同的功能的方式。我使用的是.NET 4.0,但對4.5是否更容易使用感興趣。
在4.5中,您可以通過await/async功能執行此操作,並通過在異步函數內部一起插入任務來嘗試/捕獲 – Carsten 2012-03-06 16:48:33
我最近遇到了同樣的問題,並沿着相同的路線前進,直到找到Stephen的博客文章Toub Gideon的答案鏈接到。它比我最初嘗試解決方案時更清晰,更明顯地處理所有的角落案例。 – shambulator 2012-03-08 15:49:35