Easy and Simple way to start a new task in C#

I recently look for an easy way to start a new task in C#. Many of the examples that I found required several lines of code. Then I found the simple example below:

Task.Run(() => {
   //TODO add your code here
});

This starts a new task and let's your code run within it. In the example above I am not waiting for the task to finish, so the main thread will go past it. Often you would like to have some control of what is happening in the task, such as knowing when it is finished, but the above could make sense if you wish to run things in parallel. There is also the possibility of canceling the Task, using a cancellation token. This can be passed around in your application, so that all tasks in the application uses the same cancellation token and they can all be canceled ("around the same time").

Below I have made a small example with two tasks, which I created while playing around with this.

using (var tokenSource = new CancellationTokenSource())
{
    Task.Run(() => {
        Console.WriteLine("Stop in 1 sec");
        Thread.Sleep(1000);
        tokenSource.Cancel();
        Console.WriteLine("Stopped");
    });

    Task.Run(() => {
        while (true)
        {
            if (tokenSource.IsCancellationRequested)
                break;
            Console.WriteLine("In while loop");
        }
    }).Wait();
}

Tasks uses threads from the threadpool, which is a reusable pool of threads as it can be expensive to create new threads.

I hope you liked this post on tasks, let me know in the comments if it was helpful!