C# - Infinite loop

An "infinite loop" in C# is a loop that has no end - it continues to execute indefinitely because the loop's terminating condition is never met or because it lacks such a condition altogether. Infinite loops are typically used intentionally in cases where a program should run continuously until it is manually stopped (such as a server process), or they can be a result of a programming error.


using System;

class InfiniteLoopExample
{
    static void Main()
    {
        // This is an infinite loop
        while (true)
        {
            Console.WriteLine("Looping infinitely...");
            
            // Adding a sleep delay so that the output is readable
            System.Threading.Thread.Sleep(1000);
        }
    }
}
    
Program Output

If you run this program, it will output "Looping infinitely..." to the console window once every second, and it will keep doing so until you manually stop the program (e.g., by pressing Ctrl+C in the console, or stopping the process in your IDE).

Please note that running an infinite loop like this on purpose should be done with caution, as it can make your program unresponsive or consume unnecessary system resources. The Thread.Sleep(1000); call is added to slow down the loop, causing it to wait for 1000 milliseconds (1 second) before printing the message again. This reduces the impact on system resources.


Looping infinitely...
Looping infinitely...
Looping infinitely...
Looping infinitely...
...
    

And it would continue to do so until you intervene to stop the execution.

To break out of an infinite loop, you can use various techniques:

1. Using break statement:

You can use the break statement within the loop body to exit the loop based on a specific condition. For example:


while (true)
{
    // Code to be executed

    if (condition)
    {
        break; // Exit the loop
    }
}
2. Modifying the loop condition:

You can modify the loop condition within the loop body to make it eventually become false, allowing the loop to terminate. For example:


while (true)
{
    // Code to be executed

    if (condition)
    {
        // Modify the loop condition
        break;
    }
}
3. Using return statement:

If the infinite loop is within a method, you can use the return statement to exit the method and terminate the loop. For example:


void MyMethod()
{
    while (true)
    {
        // Code to be executed

        if (condition)
        {
            return; // Exit the method and terminate the loop
        }
    }
}

It is crucial to ensure that any loops you create have a well-defined termination condition to prevent unintentional infinite loops that can negatively impact the performance and functionality of your program.