Skip to main content

New threads can be started using the Task Programming Library in .NET in (at least) 5 different ways.

using System.Threading.Tasks;

//
// The most direct way
Task.Factory.StartNew(() =>
{
    Console.WriteLine("Hello Task library!");
});

//
// Using Action... where PrintMessage is a method:
void PrintMessage()
{
    Console.WriteLine("Hello Task library!");
}
Task task = new Task(new Action(PrintMessage));
task.Start();

//
// Using a delegate
Task task = new Task(delegate
{
    PrintMessage();
});
task.Start();

// Lambda and named method
Task task = new Task(() => PrintMessage());
task.Start();

// Lambda and anonymous method
Task task = new Task(() =>
{
    PrintMessage();
});
task.Start();

// Using Task.Run in .NET4.5
public async Task DoWork()
{
    await Task.Run(() => PrintMessage());
}

// Using Task.FromResult in .NET4.5 to return a result from a Task
public int GetSum(int a, int b)
{
    return a + b;
}
public async Task DoWork()
{
    int res = await Task.FromResult<int>(GetSum(4, 5));
}