Click here to Skip to main content
Click here to Skip to main content

Don't waste time! Synchronize your ThreadPool.

, 7 Jul 2005
Rate this:
Please Sign up or sign in to vote.
This article is about some fun with ThreadPool. You can make the thread work even when it is waiting.

Introduction to ThreadPool

At the outset, let me tell what a threadpool is. Thread Pooling is an infrastructure that maintains and monitors multiple threads created by one or more applications in your system. It offers you a pool (collection) of worker threads that are managed by the system.

Most of the time, threads are in the sleeping state, as the system is idle, waiting for an event to occur. Once there is a change or update status information, they get awakened and start working what they intend to run. With the setup provided by ThreadPool, one thread monitors the status of several wait operations queued in to the thread pool. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function. Polling activates them selectively and periodically.

A thread pool is created the first time you create an instance of the ThreadPool class. The thread pool has a default limit of 25 threads per available processor that could be changed using CorSetMaxThreads as defined in the mscoree.h file. Each thread uses the default stack size and runs at the default priority. Each process can have only one operating system thread pool.

WaitHandle

This class is typically used as a base class for synchronization objects. WaitHandle is an object that controls the waiting threads. It uses a signaling mechanism to indicate taking or releasing exclusive access to a shared resource. At the same time, it also blocks the thread while waiting for access to shared resources until one or more synchronization objects receive a signal.

AutoResetEvent

This class is derived from WaitHandle and is used to notify a waiting thread that an event has occurred. It allows threads to communicate with each other by signaling.

If the AutoResetEvent is in the nonsignaled state, the thread blocks, waiting for the thread that currently controls the resource to signal that the resource is available by calling the Set method. Calling Set signals AutoResetEvent to release a waiting thread. AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the nonsignaled state.

RegisterWaitForCallback Method

You need to supply values to the following parameters:

  1. WaitObject of WaitHandle type used to register the callback method.
  2. WaitOrTimerCallback delegate to call when the waitObject is signaled.
  3. Object passed to the delegate.
  4. Time-out represented by a TimeSpan. If timeout is zero, the function tests the object's state and returns immediately. If timeout is -1, the function's time-out interval never elapses.
  5. Boolean value "true" to indicate the thread will no longer wait on the waitObject parameter after the delegate has been called; false to indicate the timer is reset every time the wait operation completes until the wait is unregistered.

The RegisterWaitForSingleObject method queues up the specified delegate-method to the thread pool. A worker thread will execute the delegate when one of the following occurs:

  1. The specified object is in the signaled state. You can call the "Set" method of the AutoResetEvent object. (Commented out in the example shown in this article).
  2. The time-out interval elapses.

To cancel the wait operation, you can always call the RegisteredWaitHandle.Unregister method.

    class testclass
    {
        public void show(Object O)
        {
            Console.WriteLine("Welcome to C#", "TestClass1 Object");
        }
    }

    class testclass1
    {
        public void show(Object O)
        {
            Console.WriteLine("Welcome to ThreadPool", "TestClass2 Object");
        }
    }
    class WorkClass
    {
        static int CountDown= 20;
        public static void WaitToShow(Object Obj, bool signaled)
        {
            if (Obj != null)
                Console.WriteLine(i--);
    }

The first two classes defined above are used for demonstrating the QueueUserWorkItem of ThreadPool. The method show defined in these two classes is the callback method to be called by the thread. The WaitToShow method in the example class is used as a callback method during wait time. The countdown value is initialized to 20.

        public static void Main()
        {
            AutoResetEvent MyEvent = new AutoResetEvent(false);
            testclass t1 = new testclass();
            testclass1 t2 = new testclass1();
            ThreadPool.RegisterWaitForSingleObject(MyEvent, 
              new WaitOrTimerCallback(WaitToShow),t1,500,false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(t1.show));
            ThreadPool.QueueUserWorkItem(new WaitCallback(t2.show));
        //    Myevent.Set();
            Console.WriteLine("****Top 20 CountDown Program******");
            Thread.Sleep(10000);            }
    }
}

In the above code, an instance for the wait handle, AutoResetEvent, is created. The instance of testclass1 (t1) is registered with the WaitOrTimerCallback delegate. After queuing the work items, the thread goes into sleep mode for 10000 milliseconds. During this wait time, WaitToShow is executed for every 500 milliseconds. I could print the countdown of numbers from 20 to 1 during this time.

Note that a call to MyEvent.Set has been commented out. WaitOrTimerCallback delegate is invoked at regular intervals of 500ms instead of signaling the waithandle MyEvent.

The output of the above program is as follows:

****Top 20 Countdown Program******
Welcome to C#
Welcome to ThreadPool
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1

Summary

It is really amazing that a ThreadPool thread calls a method at regular intervals during wait time.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Balamurali Balaji
Founder BB Systems CIT-GPNP
India India
No Biography provided

Comments and Discussions

 
Generalreply to senthil PinmemberBalamurali Balaji7-Jul-05 23:50 
GeneralRe: reply to senthil PinmemberMember 461617314-May-08 3:54 
GeneralArticle Title PinmemberS. Senthil Kumar7-Jul-05 6:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 7 Jul 2005
Article Copyright 2005 by Balamurali Balaji
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid