7

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)

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..");
            }
        }
    }
2
  • Because it keeps evaluating loop as fast as it possibly can.
    – Rodrigo
    Commented Jul 31, 2014 at 5:01
  • 4
    I think downvotes on this question are unfair. Just because it is obvious to experienced engineers does not mean it is obvious to all. There are subtle issues of blocking I/O here that the question brings up. Commented Jul 31, 2014 at 5:03

4 Answers 4

7

Console.WriteLine is a blocking (interruptable) I/O call, so other things can happen while the processor is blocked on I/O. In fact, it spends significantly more time blocked on I/O than it does evaluating the trivial condition true and jumping!

Without the writeline call, your processor is completely busy and cannot be interrupted.

Try replacing Console.WriteLine with something like int x = 1, or anything that does not block. This should behave like the empty body case.

1
  • Good answer. I like your int x = 1 experiment. +1. Commented Jul 31, 2014 at 5:05
2

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.

You may also like to check Halt and Catch Fire

On a side note:

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.

2

The CPU spends all its time checking that true is true, and the compiler didn't optimize it away. With the WriteLine, the process can block when writing to the console, which reduces overall CPU usage.

2

When the line is commented out the while loop does nothing and just consumes CPU spinning in a circle. When you call WriteLine your program makes a call to the operating system which suspends your process temporarily. This leads to your program being "blocked" for most of the time and consuming CPU only between write() system calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.