Figure 1 - Animated Gifs running in a ThreadPool
One of the nice features incorporated into the .NET framework is the ThreadPool class. If you are not in the mood to manage your threads (determining when they sleep and when they wake up), you can take advantage of this powerful class consisting of some easy to use static functions. In this article we will discuss the use of the ThreadPool class in conjunction with the ImageAnimator class to run 3 animated gifs in separate threads.
The great thing about the ThreadPool class is you dont really have to deal with threads directly. There are two main methods used in this example from the ThreadPool class, each one is described below.
| ThreadPool Static Methods |
Description |
| RegisterWaitForSingleObject |
Used to trigger an Asynchronous callback with an event, if the event doesnt occur in the time out period, it triggers anyway. |
| QueueUserWorkItem |
Used to put a new worker thread in the thread pool along with an associated object. |
Table 1 - ThreadPool class methods
ThreadPools have an added advantage over the thread class in that, not only do they allow you to create a thread, but also it lets you pass an object associated with the thread to the thread delegate. I havent figured out how to do this with the Thread class yet. Perhaps in the future, the .NET framework will be more accommodating with this task.
The object you pass into your delegate can be just about anything since it can box the instance of your class. When you call QueueUserWorkItem, you pass in the delegate for your thread as the first parameter, and the associated object as your second parameter.
RegisterWaitForSingleObject has a different purpose. It allows you to trigger a callback function with a WaitHandle or AutoResetEvent. The WaitHandle lets you do things like trigger the callback