Tasks and Parallel Library – the TPL
The TPL has been around for quite some time. It was introduced back in 2010 with the release of .NET 4.0.
The TPL simplifies many of the things we used to do with threads. Threads still have their place, especially when dealing with third-party libraries. However, in most cases, we can let the TPL figure things out.
In the TPL, the Task
class is the main class to work with. Task
is a class that handles the instantiation of threads when needed. It does much more, but we will deal with that later.
I said “when needed” because it is smart enough to determine when a new thread is needed.
Let us begin with a straightforward example and then work from there:
Task myTask = Task.Run(() => { Console.WriteLine("Hello from the task."); }); Console.WriteLine("Main thread is done."); Console.ReadKey();
Task
is just another C# class that handles much of the concurrency for us. In this case, we call...