views:

1219

answers:

3

What is the exact purpose of WaitCallback delegate ?

WaitCallback callback = new WaitCallback(PrintMessage);
ThreadPool.QueueUserWorkItem(callback,"Hello");

static void PrintMessage(object obj)
{
   Console.WriteLine(obj);
}

Can i mean "Wait" in the "TheadPool" until thread is availabe.Once it is available execute the target?

A: 

Yes, your callback method executes when a thread pool thread becomes available. For eg, in this example, you can see I'm passing the PooledProc as the call back pointer. This is called when the main thread sleeps.

public static void Main()
    {

        ThreadPool.QueueUserWorkItem(new WaitCallback(PooledProc));
        Console.WriteLine("Main thread");            
        Thread.Sleep(1000);
        Console.WriteLine("Done from Main thread");
        Console.ReadLine();
    }

    // This thread procedure performs the task.
    static void PooledProc(Object stateInfo)
    {         
        Console.WriteLine("Pooled Proc");
    }

Obviously, the paramter type of QueueUserWorkItem is a WaitCallback delegate type, and if you examine, you may note that the signature of WaitCallBack is like

public delegate void WaitCallback(object state);

The PooleProc method is having the same signature, and hence we can pass the same for the callback.

amazedsaint
+2  A: 

The WaitCallback in this case represents a pointer to a function that will be executed on a thread from the thread pool. If no thread is available it will wait until one gets freed.

Darin Dimitrov
If no thread become available for infinite time,how do i know ?
Using `QueueUserWorkItem` you can't know. You must use `RegisterWaitForSingleObject` method (http://msdn.microsoft.com/en-us/library/system.threading.threadpool.registerwaitforsingleobject.aspx)
Darin Dimitrov
A: 

From msdn

WaitCallback represents a callback method that you want to execute on a ThreadPool thread. Create the delegate by passing your callback method to the WaitCallback constructor.

Queue your task for execution by passing the WaitCallback delegate to ThreadPool..::.QueueUserWorkItem. Your callback method executes when a thread pool thread becomes available.

System.Threading.WaitCallBack

A.m.a.L