Thread.Sleep or Thread.Yield

后端 未结 1 1810
野性不改
野性不改 2020-12-09 01:46

I have a method that uses a background worker to poll a DLL for a status looking something like this:

var timeout = DateTime.Now.AddSeconds(3);
while (System         


        
相关标签:
1条回答
  • 2020-12-09 02:33

    Thread.Yield will interrupt the current thread to allow other threads to do work. However, if they do not have any work to do, your thread will soon be rescheduled and will continue to poll, thus 100% utilization of 1 core.

    Causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

    Thread.Sleep will schedule your thread to run again after the sleep time expires, thus much lower CPU utilization.

    Blocks the current thread for the specified number of milliseconds.

    Given the choice between the two, Thread.Sleep is better suited for your task. However, I agree with the comment from @Bryan that a Threading.Timer makes for a more elegant solution.

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