Thread.Sleep(0) : What is the normal behavior?

后端 未结 5 1391
渐次进展
渐次进展 2020-12-05 10:13

To my understanding a Thread.Sleep(0) force a context switch on the OS.

I wanted to check what was the maximum amount of time that could pass in an application befor

5条回答
  •  时光取名叫无心
    2020-12-05 10:41

    I was bitten by this bug in a previous project. I had a thread running which would check messages in a prioritized queue, looking for a new one. If it found no new message, I wanted the thread to go to sleep until a message's being added to the queue would wake it back up to check again.

    Naively, assuming that Thread.Sleep(0) would cause the thread to go to sleep until woken up again, I found our app consuming crazy amounts of CPU once messages started coming in.

    After a few days of sleuthing possible causes, we found the info from this link. The quick fix was to use Thread.Sleep(1). The link has the details around the reason for the difference, including a little test app at the bottom, demonstrating what happens to performance between the 2 options.

提交回复
热议问题