2 ways to create a Task in C#
Task is a unit of work which is being executed on a separate thread by the scheduler.
Programmer will no longer have to manage the low level threads. A thread from the thread pool will execute the created task.
Following are the ways to create tasks :-
- In the following code, we are creating and running the task in some other thread.
Task.Factory.StartNew(() =>
{
Console.WriteLine("Some work done.");
});
2. In the following code, we are first creating the task and then starting it to run it on another thread.
var task = new Task(() => Console.WriteLine("Some work done."));
task.Start();
Lets’ jump into some details.
- StartNew method which we have used takes an Action delegate as an argument.
public Task StartNew(Action action)
It means either we can pass
- A delegate as an argument
Action action = () => Console.WriteLine("Some work done.");
Task.Factory.StartNew(action);
2. Or a function which takes no argument and returns nothing.
Task.Factory.StartNew(() =>
{
Console.WriteLine("Some work done.");
});
Overall, there are 2 ways to create the task and run it as explained in the first half of the articles.