Task.WaitAll() not working as expected

前端 未结 3 2144
暗喜
暗喜 2021-01-05 19:37

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

相关标签:
3条回答
  • 2021-01-05 19:55

    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.

    0 讨论(0)
  • 2021-01-05 20:14

    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.

    0 讨论(0)
  • 2021-01-05 20:17

    Because it waits as your threads finish. They run exactly 3 seconds 300X10

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