mardi 3 mars 2015

How to wait for multiple Tasks without blocking the GUI?

In a C# .NET 4.0 Windows Forms GUI application, in response to a button being clicked I need to spawn a large number of processes and show them in a list box. As each process ends it should be removed from the list and when all processes are done, something should happen.


Since it's 4.0 I think using Task is the best route but I can't just run up a bunch of tasks and call Task.WaitAll because that would block the main UI thread, as the button click handler wouldn't return.


What is the nicest way to implement this? I can see two main options:



  1. The button handler starts one task, which runs all the other tasks and waits for them to complete.

  2. I don't use Task.WaitAll - as each Task completes it checks (or tells the application to check) if all the tasks are complete or not.


But is there a standard/preferred solution here using the TPL?


Also - can a Task update my form GUI or do I need to decouple Task-GUI interaction, e.g. when a Task completes it fires an event on the Form?


Pseudo-code would be great - I'm new to TPL and much of the fun stuff available in .NET 4.0.


Aucun commentaire:

Enregistrer un commentaire