Thread Pool in ASP.Net C#

What Is Multithreading?

Multithreading is a technique that can be used to perform time consuming tasks in a separate additional thread other than the main application thread.

The Thread Pool

Instead of creating a thread each time we need one, and then destroying it after finishing, the .NET framework introduces the concept of thread pool. In the thread pool technique, and instead of creating a new thread whenever you need one, your application will obtain a thread from the thread pool. After that obtained thread completes its task, it will be returned to the thread pool instead of destroying it - waiting for the next acquiring. This reusability increases the overall application performance, and reduces the cost of excessive thread creation and termination.

To make use of this technique, you need to use the System.Threading.ThreadPool class. The thread pool will be created the first time you use it. The number of total threads in this pool is restricted by default to 25 threads. This means that all of these 25 threads may be busy at some point. If you need to acquire a new thread at this point, your task will be scheduled waiting for a thread to finish its task and return to the pool.

Benefits of Using the Thread Pool

Using the thread pool is the easiest technique you can use to create a multithreaded application for the following reasons:
  • You do not have to create, manage, schedule, and terminate your thread, the thread pool class do all of this for you.
  • There is no worries about creating too many threads and hence affecting system performance. Thread pool size is constrained by the .NET runtime. The number of threads you can use at the same time is limited.
  • You need to write less code, because the .NET framework manages your thread internally with a set of well tested, and bug free routines.

Limitations of Using the Thread Pool

Despite the ease of use, the thread pool has the following limitations or disadvantages when compared to manually managing your threads:
  • With thread pool, you have no control over the state and priority of the thread.
  • With thread pool, you can not give a stable identity to your thread and keep tracking it.
  • When submitting a process to the thread pool, you have no idea when the process will be executed. Your process may be delayed when there are high demand on the thread pool.
  • The thread pool is not suitable when you want to run two tasks or processes using two threads, and need these two tasks to be processed simultaneously in a deterministic fashion.
  • The .NET framework uses the thread pool for asynchronous operations, and this places additional demand on the limited number of available threads.
  • Despite of robust application isolation, there are situations where your application code can be affected by another application code.
Tags: , ,
Hot on Web:


About author