7 Ways to create tasks in .NET C#

If you are programming in C# (.NET) and you are in the situation of having to create and execute a Task in a new thread, you can proceed in many different ways.


First you add the following using directive:

 using System.Threading.Tasks;

 

Use one of the following methods:

 

  1. Classic Method
Task.Factory.StartNew(() => { Console.WriteLine(“Hello Task :D”); });

 

  1. Using Delegate
Task task = new Task(delegate { MyVariousCommands(); });
task.Start();

 

  1. Using Action
Task task = new Task(new Action(MyMethod));
task.Start();

where MyMethod it is a real method:

private void MyMethod()
{
Console.WriteLine(“Hello Task :D”);
}

 

  1. Using Lambda with no method
Task task = new Task( () => { MyVariousCommands(); } );
task.Start();

 

  1. Using Lambda with a method
Task task = new Task( () => MyMethod() );
task.Start();

 

  1. Using Run (.NET 4.5)
public async Task DoStuff()
{
await Task.Run(() => MyMethod());
}

 

  1. Using FromResult (.NET 4.5)
public async Task DoStuff()
{
int result = await Task.FromResult<int>(SumMe(1, 2));
}

private int SumMe(int a, int b)
{
return a + b;
}

 

Remember that it is not possible to start a Task that has already been executed.

 

In this case (if you have to re-execute the same Task) you will have to re-initialize the Task before you can re-execute it.

 

Share on Social Media
Scroll to Top