Tasks
Learn to use the Task Parallel Library (TPL) and the Task class to execute code asynchronously on the Thread Pool and manage task lifecycles.
In the previous lesson, we used ThreadPool.QueueUserWorkItem to run code in the background. While efficient, it had a major limitation: we had no easy way to know when the background thread finished. This forced us to use Thread.Sleep to prevent the application from closing.
To solve this, .NET provides the Task Parallel Library (TPL). The TPL is based on the Task, which represents an asynchronous operation.
Think of a Task as an object representing an asynchronous operation running on the Thread Pool that provides:
Status tracking: Know if the work is running, completed, or failed.
Control: Wait for the work to finish.
Return values: Return a result from the background operation.
Creating and running tasks
The standard way to start a new task in modern C# is using the static Task.Run method. This method queues the specified work to run on the Thread Pool and immediately returns a Task object representing that operation.