Is “while (true)” usually used for a permanent thread?

后端 未结 6 1157
温柔的废话
温柔的废话 2021-02-04 07:18

I\'m relatively new to coding; most of my \"work\" has been just simple GUI apps that only function for one thing, so I haven\'t had to thread much.

Anyway, one thing I\

6条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 08:08

    I had the same problem and tried several methods, keeping an eye on the CPU % which in my case was really important. Here the results:

    while (true) {} //this is the worst CPU-consuming one: 30% in my case.
    

    The above, in terms of performance, is the worst (takes more CPU % than any other method, 30% on my project, on my pc). Much better the next one:

    while (true) {thread.sleep(1);} //5% cpu, in my case
    

    The above is good in terms of CPU % (around 5% in my case), but not very much elegant:

    Console.Readline(); //4% cpu in my case, but for very specific projects
    

    The above is usable only in specific cases, and it's good if you have a console .net application running on background that will never be able to capture a keypress. Still not much elegant, but takes around 4% of CPU in my particular case.

    ManualResetEvent resetEvent = new ManualResetEvent(false);
    resetEvent.WaitOne(); // WINNER: 4% cpu in my case, and very elegant also.
    

    The above, in my opinion, is the best one: elegant and low CPU consuming (4% in my case). You simply wait for a resetEvent that will never happen. Low CPU% on waiting, and elegant. Also, you can make terminate the infinite waiting by calling "resetEvent.Set()", even from another thread...

提交回复
热议问题