Tasks
Learn to run background jobs with the help of tasks.
We'll cover the following
Introduction
In addition to the ThreadPool
class, there’s another way to use a pool’s threads. With the help of the Task Parallel Library (TPL), we can asynchronously execute methods that we want to run in the background. The TPL library is based on the concept of tasks, each of which describes a separate operation. Tasks are represented by the Task
class that resides in the System.Threading.Tasks
namespace. This class encapsulates a method that executes asynchronously (without blocking the main thread) on a pool’s thread.
We create new threads using the Thread
class for long-term jobs that keep the application running, even when other threads finish executing. Thread pool threads, on the other hand, are useful for jobs that run constantly but for shorter amounts of time. Because threads are reused and not destroyed, performance doesn’t deteriorate. TPL is an abstraction over thread pool threads, so performance notes apply here as well. However, TPL has one major feature that other multithreading approaches lack: tasks can return value. Therefore, if we need our methods to run on background threads and return value once they’re done, TPL is the best option. This lesson, however, focuses on methods that have the void
return type.
Create tasks
There are several ways to create instances of Task
and run methods asynchronously. The first option is to instantiate using a constructor and provide it with an instance of the Action
delegate (or any method that conforms to this delegate):
Task task = new Task(SomeMethod);
task.Start();
public void SomeMethod()
{
Console.WriteLine("Executed inside a task");
}
We call the Start()
method to begin execution. Anonymous methods that conform to the Action
delegate can also be passed to the Task
constructor:
Get hands-on with 1400+ tech skills courses.