7 ways to start a Task in .NET C#
January 1, 2014 39 Comments
New threads can be started using the Task Programming Library in .NET in – at last – 5 different ways.
You’ll first need to add the following using statement:
using System.Threading.Tasks;
The most direct way
Task.Factory.StartNew(() => {Console.WriteLine("Hello Task library!"); });
Using Action
Task task = new Task(new Action(PrintMessage)); task.Start();
…where PrintMessage is a method:
private void PrintMessage()
{
Console.WriteLine("Hello Task library!");
}
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 async Task DoWork()
{
int res = await Task.FromResult<int>(GetSum(4, 5));
}
private int GetSum(int a, int b)
{
return a + b;
}
You cannot start a task that has already completed. If you need to run the same task you’ll need to initialise it again.
View the list of posts on the Task Parallel Library here.