C # WaitCallBack - ThreadPool

What is the purpose of the WaitCallback delegate?

WaitCallback callback = new WaitCallback(PrintMessage); ThreadPool.QueueUserWorkItem(callback,"Hello"); static void PrintMessage(object obj) { Console.WriteLine(obj); } 

Can I "Wait" in "TheadPool" until the stream is available. Once it is available, complete the goal?

+4
source share
3 answers

WaitCallback in this case is a pointer to a function that will be executed in the thread from the thread pool. If the thread is not available, it will wait until it is released.

+9
source

Yes, your callback method is executed when the thread stream thread becomes available. In this example, you can see that I am passing PooledProc as a callback pointer. This is called when the main thread is sleeping.

 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 QueueUserWorkItem is the delegate type WaitCallback, and if you examine it, you may notice that the WaitCallBack signature is similar:

 public delegate void WaitCallback(object state); 

The PooledProc method has the same signature, and therefore, we can pass the same for the callback.

+1
source

From msdn

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

Queue the task by passing the WaitCallback delegate to ThreadPool .. ::. QueueUserWorkItem. Your callback method is executed when a thread pool thread becomes available.

System.Threading.WaitCallBack

+1
source

All Articles