Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for QueueUserWorkItem to Complete

Tags:

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.

like image 756
PedroC88 Avatar asked Jun 30 '11 03:06

PedroC88


People also ask

What is ThreadPool QueueUserWorkItem?

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.

What is WaitHandle?

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.

What is WaitCallback C#?

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.


1 Answers

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()); 
like image 145
Alex Aza Avatar answered Oct 20 '22 08:10

Alex Aza