With the new TaskFactory class from .Net 4.0 it has become incredibly easy to manage dependencies between multiple tasks.
In below code sample, the TaskFactory receive 6 tasks to execute. Additional logic is added as:
- Task A will only be run when Task B and C are completed.
- Task C will only be run when Task F, E or D is completed.
If you are confused with the ‘=>’ have a look at lambda expression.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TasksDemo
{
class Program
{
static void Main(string[] args)
{
UseTask demoTask = new UseTask();
Console.ReadKey();
}
}
class UseTask
{
public UseTask()
{
// Set the TaskFactory - Create and schedule objects
var tf = new TaskFactory(
TaskCreationOptions.AttachedToParent,
TaskContinuationOptions.AttachedToParent);
var F = tf.StartNew(() => DoSomething(‘F’));
var E = tf.StartNew(() => DoSomething(‘E’));
var D = tf.StartNew(() => DoSomething(‘D’));
// C will be started only when F, E or D has been completed
var C = tf.ContinueWhenAny(new Task[]{F, E, D}, tasks => DoSomething(‘C’));
var B = tf.StartNew(() => DoSomething(‘B’));
// A will only happens once B and C are completed.
var A = tf.ContinueWhenAll(new Task[] {B, C}, tasks => DoSomething(‘A’));
}
private void DoSomething(char @char)
{
Console.WriteLine(“DoSomething called - {0}”, @char);
Random rd = new Random();
Thread.Sleep(rd.Next(1000, 3000));
Console.WriteLine(“DoSomething called - {0} - DONE”, @char);
}
}
}
Isn’t that beautiful?
