Attached and Detached Child Tasks in C#
Task can be defined as an object representing some work which needs to be done. System.Threading.Tasks is library provided by .net framework for tasks. Task class have it's own set of properties and methods defined in it.
Tasks share parent child relationship among themselves. A task is said to be parent task if it contains another task instance. Child tasks can be categorised into following :
Attached child tasks :- Attached child tasks are the tasks within another task created with "TaskCreationOptions.AttachedToParent" option where parent task wait for attached child tasks to complete.
Example to demonstrate attached child task :-
using System;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
public static void Main()
{
var parent = Task.Factory.StartNew(() => {
Console.WriteLine("Parent task starts.");
var child = Task.Factory.StartNew(() => {
Console.WriteLine("Attached child task starts.");
Console.WriteLine("Attached child task completed.");
}, TaskCreationOptions.AttachedToParent);
});
parent.Wait();
Console.WriteLine("Parent task completed.");
Console.ReadKey();
}
}
}
Output:
In above program parent task is creating a simple child task via "TaskCreationOptions.AttachedToParent" option. Whenever above program is executed output will always remain same as parent task will always finish after child task finish executing .
Detached child tasks :- Detached child tasks are the tasks within another task that are executed independently of it's parent task i.e parent task need not to wait for child task to complete.
Example to demonstrate detached child task :-
using System;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
public static void Main()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Parent task executing.");
var child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Child task starts.");
Console.WriteLine("Child task completed.");
});
});
parent.Wait();
Console.WriteLine("Parent task completed.");
Console.ReadKey();
}
}
}
In above program parent task is creating a simple child task which is a detached child task. Whenever this program with detached child task is run different output is obtained each time because parent and child task are executing independently of each other . This program only wait for parent task to complete(parent.Wait()), child task may or may not execute before application terminates.
Two outputs which can be obtained :
Output 1 :-
Output 2 :-
0 Comment(s)