Is Thread.Sleep(Timeout.Infinite); more efficient than while(true){}?

前端 未结 6 863
Happy的楠姐
Happy的楠姐 2020-12-09 02:46

I have a console application that I would like to keep open all of the time while still listening in to events. I have tested Thread.Sleep(Timeout.Infinite); an

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 03:19

    Yes, while(true) consumes CPU while sleep() works in a smarter way: The sleep() function puts the current execution context to sleep; it does this by calling a syscall to invoke the kernel sleep function which atomically
    (a) sets a wake-up timer
    (b) marks the current process as sleeping
    (c) waits until the wakeup-timer fires or an interrupt occurs

    If you call sleep(), the CPU can do other work.

    That's one reason why sleep() is useful.

    A useful link - Be careful when using Sleep

提交回复
热议问题