Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of MsgWaitForMultipleObjects?

I have a Windows Form with a ListView in Report Mode. For each item in the view, I need to perform a long running operation, the result of which is a number.

The way I would do this in native win32 is to create a worker thread for each item (naively; of course I won't create an unbounded number of threads) and then MsgWaitForMultipleObjects() on the array of thread handles. As each calculation finishes, the threads signal and the main UI thread wakes up and updates. In the mean time, we pump messages so the UI thread remains responsive.

Can anyone provide an example of how this might work in C#? I've looked at the Monitor object, and it doesn't seem to be what I want—or does it pump messages while blocking?

Thanks.

Edit: It seems that WaitHandler.WaitAny() might actually pump messages. See cbrumme's treatise on message pumping in the CLR.

like image 325
i_am_jorf Avatar asked Feb 21 '10 23:02

i_am_jorf


1 Answers

Have your main thread create a manager thread. You could use the BackgroundWorker for this. This manager thread kicks off a worker thread for each item in the ListView. This will allow your UI to keep responding to user input without hanging while the background threads are processing.

Now, the problem is how to wait for each worker thread to finish. Unfortunately, I have been unable to find a way to get a thread handle for System.Threading.Thread objects. I'm not saying there isn't a way to do it; I just haven't found one. Another complicating aspect to this is that the System.Threading.Thread class is sealed, so we can't derive from it to provide some kind of 'handle'.

This is where I use ManualResetEvent.

Let's say each worker thread is simply a ThreadPool thread. The managing BackgroundWorker creates a ManualResetEvent object for each item in the ListView. As the BackgroundWorker launches each ThreadPool thread, pass the ManualResetEvent as an argument to the QueueUserWorkItem function. Then, just before each ThreadPool thread exits, set the ManualResetEvent object.

The BackgroundWorker thread can then put all of the ManualResetEvent objects in an array and wait on that array using the WaitHandle.WaitXXX functions. As each thread finishes, you can use the BackgroundWorker's events to update the UI or you can use the Control.Invoke() technique to update the UI (see Marc Gravell's answer here).

Hope this helps.

like image 182
Matt Davis Avatar answered Nov 13 '22 01:11

Matt Davis