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.
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.