Thread Pools C# Help

Creating threads takes time. When you have different short tasks to do, you can create a number of threads in advance and send requests as they should be done. It would be nice if this number increased as more threads were needed and decreased as needed to release resources.

There is no need to create such a list on your own. The list is managed by the ThreadPool class. This class increases and decreases the  umber of threads in the pool as they are needed, up to the maximum number of threads. The maximum number of threads in a pool is configurable. With a ,dualcore CPU, the default number is set to 50 worker threads and 1,000 I/O threads. You can specify

the minimum number of threads that should be started immediately when the pool is created and the maximum number of threads that are available in the pool. H there are more jobs to process, and the maximum number of threads in the pool has already been reached, the newest jobs are queued and must wait for a thread to complete its work.

The sample application first reads the maximum number of worker and I/O threads and writes this information to the console. Then in a for loop, the method JobForAThread () is assigned to a thread from the thread pool by invoking the method ThreadPool .QueueUserWorJcI tern() and passing a delegate of type Wai tCallback. The thread pool receives this request and selects one of the threads from the pool to invoke the method. H the pool is not already running. the pool is created and the first thread is started. H the pool is already running and one thread is free to do the task, the job is forwarded to this thread.

When you run the application, you can see that 50 worker threads are possible with the current settings. The five jobs are processed by just two pooled threads. Your experience may be different, and you can
also change the sleep time with the job and the number of jobs to process to get very different results

Thread pools are very easy to use. However, there are some restrictions:

¤  All thread pool threads are background threads. If all foreground threads of a process are finished, all background threads are stopped. You cannot change a pooled thread to a foreground thread.

¤   You cannot set the priority or name of a pooled thread

¤   For COM objects, all pooled threads are multithreaded apartment (MTA)threads. Many COM objects require a single-threaded apartment (STA)thread

¤   Use pooled threads only for a short task. If a thread should run all the time (for example, the spell-checker thread of Word), create a thread with the Thread class.


Posted on November 3, 2015 in Threading and Synchronization

Share the Story

Back to Top
Share This