Wednesday, February 16, 2005

Using The ThreadPool Class - 1

Rules:

(1) There can only be one ThreadPool object per application.
What this means is when the application quits, the threads in the threadpool gets destroyed as well. (They don't run in the background).

(2)The ThreadPool object is created for the first time when we call the ThreadPool.QueueUserWorkItem() method (or when a callback method is called)

Example:

public class ThreadPoolDemo


{
public void LongTask1(object obj)
{
for (int i = 0; i <= 99; i++)
Console.WriteLine("Long Task 1 is being executed");
}

public void LongTask2(object obj)
{
for (int i = 0; i <= 99; i++)
Console.WriteLine("Long Task 2 is being executed");
}

public static void Main(string[] args)
{
ThreadPoolDemo tpd = new ThreadPoolDemo();
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask1));
ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask2));
}
Console.ReadKey(false);
}
Case 1: No passing of object
The method to use to start a threadpool is the static method ThreadPool.QueueUserWorkItem(). This method has two overloaded version. The first one (as shown in the above example) takes in a WaitCallBack delegate. The signature of the delegate is


public delegate void WaitCallback( object state );
Therefore a worker method to be used in a threadpool must have a return value of void and an object for argument).

Usage:
ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask1));

Case 2: Pass One Object
You can use an object to encapsulate all the input and output parameters to be passed to a thread in the threadpool. The signature of the overloaded QueueUserWorkItem() is


public static bool QueueUserWorkItem( WaitCallback callBack, object state );


Usage:
ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask1), stateObject);

0 Comments:

Post a Comment

<< Home