#TIL: Task Continuation Options

.NET has a pretty sweet framework, the Task Parallel Library, which you can use to start “tasks” that may or may not take advantage of your computer’s multiple cores while executing asynchronously. It is pretty easy to use out of the box, but also provides quite a few options for fine grained control – the task continuation options are one of those options.

You can start a new task by simply typing

1
2
var task = new Task(() => Console.WriteLine("Hello!"));
task.Start();

which is easy enough to do. What if you want to run multiple tasks, one after the other? That’s where ContinueWith comes into play:

1
2
var task = new Task(() => Console.WriteLine("I run first"));
task.ContinueWith((firstTask) => Console.WriteLine("I run second!"));

Easy as pie! What if you only want code to run if the first task completed successfully? Normally this is where you run into problems with threading – having some sort of shared state. This usually introduces race conditions, locks, and other things that increase the complexity of your code (and makes testing more difficult). But not with the TPL!

1
2
3
4
5
var task = new Task(() => Console.WriteLine("I run first"));
task.ContinueWith((firstTask) => Console.WriteLine("I only run if the first task worked"), 
  TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith((firstTask) => Console.WriteLine("I only run if there was an error"), 
  TaskContinuationOptions.OnlyOnFaulted);

Comments