Task composition and error handling using TPL

I have a method with the following structure:

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; } 

Important:

  • the task returned by InitializeAsync is not considered completed until secondTask decides
  • secondTask only works if firstTask succeeds
  • failure of either firstTask or secondTask results in a failure of the general task

I am wondering if there is a cleaner and easier way to express this, having achieved the same functionality. I am using .NET 4.0, but I am wondering if this does 4.5 either.

+7
source share
2 answers

For .NET 4.0, I used the idea of this blog article for the chain of tasks that you describe. In particular, see the Next section. Not that its version expected you to pass a function returning a task, instead of just passing a method like you to ContinueWith

Aside, Then brings you closer to SelectMany , you will need to link tasks using LINQ from the sentences. I mention this mostly as a syntax option, while async / await is in .NET 4.5, although I don't actually use it myself.

+5
source

Another option is to create your two tasks as child tasks (nested in the parent task that you will return)

The parent task will not be completed until the attached child tasks are completed. Child errors are considered parental errors.

http://msdn.microsoft.com/en-us/library/dd997417.aspx

0
source

All Articles