What is Task Parallel Library ??
These days even small devices like cellphone have multiple processors. Since the last 10–15 years, there is so much improvement in processors capability, RAM, SDD, CPU power and clock time. Which helped in running applications more efficiently and fast. The focus these days has now shifted on developers to write code that can use CPU and processors more efficiently.
Thread Quantum is the amount of time that the schedule allows a thread to run before scheduling a different thread to run.
Context Switch —?The scheduler maintains a queue of executable threads for each priority level. These are known as?ready threads. When a processor becomes available, the system performs a?context switch. The steps in a context switch are
领英推荐
TPL — Task Parallel Library
Keeping this in mind .Net introduced TPL — Task Parallel Library in framework 4.0, which is the preferred way of achieving parallelism in your code. The TPL gives you a lot of control over how your code is run, allows you to determine what happens when errors occur, provides the ability to conditionally chain multiple methods in sequence
TPL uses the .Net thread pool, but it does so much efficiently, executing multiple tasks on a single thread sequentially before returning the thread back to the pool. It saves CPU clock or thread quantum caused by small tasks and avoids the creation of new threads.
You can create a task or parallel thread of execution using Task class. It provides a callback, that we can use to define a subsequent task to run asynchronously.
If the subsequent task is very small, you may want to execute it synchronously on the same thread to avoid context switch overhead