If I add jobs to the thread pool with QueueUserWorkItem
... how do I keep my program from going forward until all jobs are completed?
I know I could add some logic to keep the app from running until all jobs are completed, but I want to know if there is something like Thread.Join()
or if there's any way to retrieve each thread that is being assigned a job.
QueueUserWorkItem(WaitCallback, Object) Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
WaitHandle is an abstract base class for the two commonly used event handles: AutoResetEvent and ManualResetEvent . Both of these classes allow one thread to "signal" one or more other threads. They're used to synchronize (or serialize activity) between threads.
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. Your method must have the signature shown here. Queue the method for execution by passing the WaitCallback delegate to ThreadPool.
You could use events to sync. Like this:
private static ManualResetEvent resetEvent = new ManualResetEvent(false); public static void Main() { ThreadPool.QueueUserWorkItem(arg => DoWork()); resetEvent.WaitOne(); } public static void DoWork() { Thread.Sleep(5000); resetEvent.Set(); }
If you don't want to embed event set into your method, you could do something like this:
var resetEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( arg => { DoWork(); resetEvent.Set(); }); resetEvent.WaitOne();
For multiple items:
var events = new List<ManualResetEvent>(); foreach(var job in jobs) { var resetEvent = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( arg => { DoWork(job); resetEvent.Set(); }); events.Add(resetEvent); } WaitHandle.WaitAll(events.ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With