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:
- Classic Method
Task.Factory.StartNew(() => { Console.WriteLine(“Hello Task :D”); });
- Using Delegate
Task task = new Task(delegate { MyVariousCommands(); }); task.Start();
- 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”); }
- Using Lambda with no method
Task task = new Task( () => { MyVariousCommands(); } ); task.Start();
- Using Lambda with a method
Task task = new Task( () => MyMethod() ); task.Start();
- Using Run (.NET 4.5)
public async Task DoStuff() { await Task.Run(() => MyMethod()); }
- 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.