Using the ThreadPool Class

Using the ThreadPool Class

When it boils down to it, one of the most common states of any application is the "idle" state. Applications spend a lot of time sitting around waiting for something to happen. They're either waiting for a user to click something on a form, or they're waiting for a request to come in on a network port like HTTP or a custom service port. Using full-fledged foreground threads when sitting around waiting for something to happen is more expensive than necessary.

To allow you to create tasks that will operate in the background, but consume the smallest amount of resources possible, the .NET Framework has the thread pool.

The thread pool uses a WaitCallback delegate instead of a ThreadStart delegate to indicate the work that should be done in the background. In addition, the thread pool makes it easy to queue up a work item and let it run. You can also pass in a state object so that you can supply a worker thread with the data it needs to perform its task without having to rely on static members or complicated scope management techniques. Without the state object being passed to a worker thread, the worker thread would need to pull its information from global or static objects. When this happens, the thread needs to worry about synchronization of that data. Using the private state object that is scoped at the thread level, there is no need for synchronization since the data belongs only to the current thread.

Listing 10.7 provides a quick illustration of how to queue a user work item. Note that you don't have to explicitly Start the background thread from the pool. The upside of the thread pool is its ease of use. However, if you need complex synchronization techniques such as events, or if you need to call Join on a list of threads as shown in preceding examples, you may find the thread pool insufficient for your needs.

Listing 10.7. Using the ThreadPool

using System; using System.Threading; using System.Collections.Generic; using System.Text; namespace ThreadPoolDemo { class Program { static void Main(string[] args) {     for (int i = 0; i < 20; i++)     {         ThreadPool.QueueUserWorkItem(             new WaitCallback(DoWork), i);     }     Console.ReadLine(); } static void DoWork(object state) {     int threadNumber = (int)state;     Console.WriteLine("Thread {0} reporting for duty.", state); } } } 

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: