This post demonstrates how to run a piece of code asynchronously in C#. This is easily achieved with the Task library. You can start a new task by using the Task.Run() method:
Task.Run(() =>
{
//Do stuff asynchronously
});
The above will start a task which does not. It is not awaited so it just runs and succeeds or fails, even though something extreme would have to happen for the above to fail. You can start multiple tasks and wait for them all using Task.Run() in combination with Task.WhenAll(). We can try this in the following example:
var stopWatch = Stopwatch.StartNew();
var task1 = Task.Run(async () =>
{
await Task.Delay(1000);
Console.WriteLine("1st done!");
});
var task2 = Task.Run(async () =>
{
await Task.Delay(2000);
Console.WriteLine("2nd done!");
});
await Task.WhenAll(task1, task2);
stopWatch.Stop();
Console.WriteLine("All done! " + stopWatch.Elapsed);
In the above we start two tasks, one is delayed for one second and the other for two seconds. After being delayed they each write the text "done!". Around it all we make a stopwatch and we expect it to take 2 seconds in total as they are running simultaneously.
The console output for the above is the following:
1st done!
2nd done!
All done! 00:00:02.0232469
So about two seconds as expected. Had we instead written it in the following way where we await each Task:
var stopWatch = Stopwatch.StartNew();
await Task.Run(async () =>
{
await Task.Delay(1000);
Console.WriteLine("1st done!");
});
await Task.Run(async () =>
{
await Task.Delay(2000);
Console.WriteLine("2nd done!");
});
stopWatch.Stop();
Console.WriteLine("All done! " + stopWatch.Elapsed);
Then it will take three seconds, since we wait for the first task to finish before we move on to the next:
1st done!
2nd done!
All done! 00:00:03.0266833
The above is the opposite of what the title of this post suggests, but it has been included to show the difference between the two.
That is all
I hope this showed you how you can create a task and not await it until later in the code. I have made another post on this topic, on how to start multiple tasks and wait for them all to finish.
Please leave a comment down below, I read all of them and maybe you have a suggestion on how the above can be improved?