.NET Framework Task: basic instantiation and Wait

Download .NET Framework for free

Example

A task can be created by directly instantiating the Task class...

var task = new Task(() =>
{
    Console.WriteLine("Task code starting...");
    Thread.Sleep(2000);
    Console.WriteLine("...task code ending!");
});

Console.WriteLine("Starting task...");
task.Start();
task.Wait();
Console.WriteLine("Task completed!");

...or by using the static Task.Run method:

Console.WriteLine("Starting task...");
var task = Task.Run(() =>
{
    Console.WriteLine("Task code starting...");
    Thread.Sleep(2000);
    Console.WriteLine("...task code ending!");
});
task.Wait();
Console.WriteLine("Task completed!");

Note that only in the first case it is necessary to explicitly invoke Start.

Task: cancelling using CancellationToken