C# WaitCallBack - ThreadPool
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 开发者_StackOverflow中文版availabe.Once it is available execute the target?
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.
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
Yes, your callback method executes when a thread pool thread becomes available. 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 parameter type of QueueUserWorkItem is a WaitCallback delegate type, and if you examine it, you may notice that the signature of WaitCallBack is like:
public delegate void WaitCallback(object state);
The PooledProc method has the same signature, and hence we can pass the same for the callback.
精彩评论