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:
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, eg 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.
If you were using .NET 4.5 you would use something like await Task.WhenAll(...)
. It can handle IEnumerable<Task>
, Task[]
and also IEnumerable<Task<TResult>>
.
If there is no way you can use .NET 4.5, you can come up with a solution of yourself, that will involve Task.ContinueWith and a counter of how many tasks are left to run, that is updated using Interlocked.Decrement
. Also, you can look at how it's done inside .NET 4.5 by looking at this source. http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,69351c6da968e5d1 . It's a bit lengthy, but it basically is what I said: tasks are continued with some other tasks that update internal counter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.