Nenad Bulatović
Nenad Bulatović

Reputation: 7444

Never ending while loop

Here is example from one C# book:

//  Timer02.cs - Displaying Date and Time
//      Using the Timer class. 
//      Press Ctrl+C or 'q' folllwed by Enter to end program. 
//------------------------------------------------------------
using System;
using System.Timers;

class myApp
{
    public static void Main()
    {
        Timer myTimer = new Timer();
        myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
        myTimer.Interval = 1000;
        myTimer.Start();


        while (Console.Read() != 'q')
        {
            ;    // do nothing...
        }
    }

    public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
    {
        Console.Write("\r{0}", DateTime.Now);
    }
}

I guess that it is supposed that loops runs until q is pressed, but when q is pressed loop is not ending.

What I am missing here?

Upvotes: 1

Views: 1391

Answers (2)

Jeffrey Kevin Pry
Jeffrey Kevin Pry

Reputation: 3296

EDIT: The method I posted never printed the message until some other key was pressed.

This will work however....

public static void Main()
    {
        Timer myTimer = new Timer();
        myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
        myTimer.Interval = 1000;
        myTimer.Start();

        while (true)
        {
            if (Console.KeyAvailable)
            {
                while (Console.ReadKey().KeyChar != 'q')
                {
                    // do nothing
                }
                break;
            }
        }
    }

The key here is to use: Console.ReadKey().KeyChar != 'q'

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504004

I suspect you didn't press return after q. The Console.Read method blocks until there's an entire line to read, even though it only actually reads a single character of that line.

From the documentation:

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

Upvotes: 4

Related Questions