What is going on with Task.Delay().Wait()?

后端 未结 3 2471
天命终不由人
天命终不由人 2021-02-20 09:59

I\'m confused why Task.Delay().Wait() takes 4x more time, then Thread.Sleep()?

E.g. task-00 was running on

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 10:10

    Neither Thread.Sleep(), nor Task.Delay() guarantee that the internal will be correct.

    Thread.Sleep() work Task.Delay() very differently. Thread.Sleep() blocks the current thread and prevents it from executing any code. Task.Delay() creates a timer that will tick when the time expires and assigns it to execution on the threadpool.

    You run your code by using Task.Run(), which will create tasks and enqueue them on the threadpool. When you use Task.Delay(), the current thread is released back on the thread pool, and it can start processing another task. In this way, multiple tasks will start faster and you will record startup times for all. Then, when the delay timers start ticking, they also exhaust the pool, and some tasks take quite longer to finish than since they started. That is why you record long times.

    When you use Thread.Sleep(), you block the current thread on the pool and it is unable to process more tasks. The Thread pool doesn't grow immediately, so new tasks just wait. Therefore, all tasks run at about the same time, which seem faster to you.

    EDIT: You use Task.Wait(). In your case, Task.Wait() tries to inline the execution on the same thread. At the same time, Task.Delay() relies on a timer that gets executed on the thread pool. Once by calling Task.Wait() you block a worker thread from the pool, second you require an available thread on the pool to complete the operation of the same worker method. When you await the Delay(), no such inlining is required, and the worker thread is immediately available to process timer events. When you Thread.Sleep, you don't have a timer to complete the worker method.

    I believe this is what causes the drastic difference in the delay.

提交回复
热议问题