What is the C# equivalent of MsgWaitForMultipleObjects?

后端 未结 2 1102
醉话见心
醉话见心 2021-02-20 13:51

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

2条回答
  •  执念已碎
    2021-02-20 14:32

    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.

提交回复
热议问题