Creating a detached child Task in .NET C#
June 6, 2017 Leave a comment
A child Task, a.k.a a nested Task, is a Task that’s started within the body of another Task. The containing Task is called the parent.
A detached child Task is one which doesn’t have any relationship with the parent. The detached child Task will be scheduled normally and will have no effect on the parent.
There’s nothing special about creating a detached child Task:
Task parent = Task.Factory.StartNew(() => { Console.WriteLine("Starting child task..."); Task childTask = Task.Factory.StartNew(() => { Console.WriteLine("Child task running and stopping for a second"); Thread.Sleep(1000); Console.WriteLine("Child task finished"); }); }); Console.WriteLine("Waiting for parent task"); parent.Wait(); Console.WriteLine("Parent task finished");
We start the parent Task within which we start a child task. You can nest the tasks as you like: the child task can have its own child task(s) which in turn can have child tasks etc.
View the list of posts on the Task Parallel Library here.