Empty Infinite While 循环的 CPU 使用率增加 [英] CPU usage increases for Empty Infinite While loop

查看:56
本文介绍了Empty Infinite While 循环的 CPU 使用率增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下为什么下面的无限循环需要大量 CPU 使用率(如果总核心数为 2,则 CPU 使用率增加了 50%,如果总 CPU 核心数仅为 1,则 CPU 使用率增加了 100%)

Can anyone explain me why the following Infinite loop takes a lot of CPU usage (CPU usage has increased upto 50% if total core is 2 and 100% if total CPU core is just 1)

但如果我取消注释该行,它会减少 1 或 2 个 CPU 使用率?

But if I un-comment the line it reduces to 1 or 2 CPU usage?

    public class Program
    {
        public static void Main(string[] args)
        {
            while (true)
            {
                //Console.WriteLine("hello..");
            }
        }
    }

推荐答案

原因是因为您的 CPU 在执行该循环时无法执行任何其他操作.CPU 不知道无限循环不是一个只需要大量迭代的复杂计算.因此,它会不断评估真实条件,从而导致 CPU 使用率增加.

The reason is because your CPU cannot do anything else while it's executing that loop. The CPU is not aware that the infinite loop isn't a complicated calculation that just requires a lot of iterations. Hence it keeps on evaluating that true condition infintely resulting in consumption of increase CPU usage.

您可能还想查看停止并着火

附注:

如果您想避免无限循环,那么您可以简单地使用 WaitHandle.要让进程从外部世界退出,请使用带有唯一字符串的 EventWaitHandle.

If you want to avoid the infinity loop then you can simply use a WaitHandle. To let the process be exited from the outer world use a EventWaitHandle with a unique string.

这篇关于Empty Infinite While 循环的 CPU 使用率增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆