Powered by Blogger.

Saturday, March 1, 2014

When to use Thread Pool class in C#.Net:




In this post we will discuss about when to use thread pool class and when not to use thread pool class.

Also check out:

- Call stored procedure in Asp.Net using C#.Net

- Read and write from Text file in Asp.Net

- Delete all stored procedures at once in SQL Server database

The situations where Thread Pool class can be applied:

- If you have lots of logical tasks that require constant processing and you want that to be done in parallel, use thread pool class.

- Use thread pools for database access, scripted tasks which runs on virtual machines that process lots of user defined tasks.

- When you want to limit the number of threads running or don't want the overhead of creating and destroying them, use a thread pool.

- The thread pool is designed to reduce context switching among the threads. Consider a process that has several components running. Each of those components could be creating worker threads. The more threads in your process, the more time is wasted on context switching. If each of these components were queued up into the thread pool, you would have a lot less context switching overhead.

- The thread pool is designed to maximize the work being done across your CPUs (or CPU cores). That is why, by default, the thread pool spins up multiple threads perprocessor.

- Normally a pool consists of 2 threads per processor (so likely 4 nowadays), however you can set up the amount of threads you want, if you know how many you need.


The situations where one should avoid thread pool:

- You require a foreground thread, all the thread pool threads are background threads.

- You require a thread to have a particular priority.

- You have tasks that cause the thread to block for long periods of time. The thread pool has a max­i­mum number of threads, so a large num­ber of blocked thread pool threads might prevent tasks from starting.

- You need to place threads into a single-threaded apart­ment(STA). All thread pool threads are in the mul­ti­threaded apartment.

- You need to have a stable identity associated with the thread, or to dedicate a thread to a task.

- If you need to make your IO related tasks concurrently such as downloading stuff from remote servers or disk access, but need to do this say once every few minutes, then make your own threads and kill them once you're finished.

- When a thread is required to be aborted prematurely.



0 comments

Post a Comment