ManualResetEvent vs. Thread.Sleep

后端 未结 2 744
南旧
南旧 2020-12-05 15:23

I implemented the following background processing thread, where Jobs is a Queue:

static void WorkThread()
{
    while (wor         


        
2条回答
  •  伪装坚强ぢ
    2020-12-05 16:07

    The events are kernel primitives provided by the OS/Kernel that's designed just for this sort of things. The kernel provides a boundary upon which you can guarantee atomic operations which is important for synchronization(Some atomicity can be done in user space too with hardware support).

    In short, when a thread waits on an event it's put on a waiting list for that event and marked as non-runnable. When the event is signaled, the kernel wakes up the ones in the waiting list and marks them as runnable and they can continue to run. It's naturally a huge benefit that a thread can wake up immediately when the event is signalled, vs sleeping for a long time and recheck the condition every now and then.

    Even one millisecond is a really really long time, you could have processed thousands of event in that time. Also the time resolution is traditionally 10ms, so sleeping less than 10ms usually just results in a 10ms sleep anyway. With an event, a thread can be woken up and scheduled immediately

提交回复
热议问题