What is the C# equivalent of MsgWaitForMultipleObjects?

后端 未结 2 1068
醉话见心
醉话见心 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:17

    The long-running active object, I think, is the best choose in your case. The main thread calls the proxy (of active object). Proxy converts the call method to the message and this message is going to a queue. Proxy returns to the caller the future object (it is a reference to the future result). The dispatcher dequeues messages one by one and realy executes your task in other thread (working thread). When working thread completes a task, it updates the result of the future object or calls callback method (for example, to update your UI).Dispather can have many working threads to execute more the one task at the same time.

    You can see this article (with sample) about long-running active object pattern.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题