2 ways to create a Task in C#

Aman Singh Parihar
1 min readDec 15, 2023

--

Task is a unit of work which is being executed on a separate thread by the scheduler.

Photo by Héctor J. Rivas on Unsplash

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 :-

  1. 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

  1. 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.

--

--

Aman Singh Parihar
Aman Singh Parihar

Written by Aman Singh Parihar

I work as a software engineer and having experience in web technologies. I like to share my knowledge with the community and aspire to learn cool things.

No responses yet