I\'m trying to figure out how to work with the Task class. In the past I have always used the regular Thread class, but I\'m trying to grasp all of the asynchronous programm
Task.WaitAll
blocks and waits for all task to complete and you are calling it on the UI thread.
All your task are trying to call richTextBox1.Invoke
(in the UI thread) but your UI thread is blocked in Task.WaitAll
. Deadlock.
You're causing a deadlock.
The UI thread is waiting for 4 tasks to be completed.
On the other hand, those 4 tasks, running calcSim
are trying to invoke code on the UI thread -> Deadlock.
You should be using Task.WhenAll()
instead. That method will return a new task that will be marked as completed when all your for tasks have completed. If you await that task, your UI thread will be freed, and so calcSim
will be able to invoke code on the UI thread, avoiding a deadlock.
Update
You're using it wrong. You're still using WaitAll
, which is a blocking call. You should replace it with WhenAll
.
await Task.WhenAll(t);
From the documentation:
Creates a task that will complete when all of the supplied tasks have completed.
By calling await
on the result, your UI thread will be free - until all 4 tasks complete. When that happens, your RunAsync3
method will resume.
Because it waits as your threads finish. They run exactly 3 seconds 300X10