Question

This is how I keep the console window open now:

private static void Main(string[] args)
{
    // Timers run here

    while(true)
    {
        Console.Read();
    }
}

But it always gets back to me: there must be a better way. The reason that Console.Read() is in an eternal while is because I don't want my program to terminate if by mistake I press enter while it's running and I'm focused on its window.

Any ideas?

Relevant questions that don't answer my question:

Was it helpful?

Solution

Given the discussions so far in comments, my first recommendation is definitely to create a System Tray application for this. This would allow for user interaction and notifications without having to keep a Console window on the desktop.

Failing that, you could perhaps implement something like a "game loop" in your console. How "real time" do the statistics need to be? One-second delayed maybe? Something like this:

while (true)
{
    Thread.Sleep(1000);
    DisplayCurrentStats();
}

This would pause the main thread (not always recommended, but it is the UI that you're trying to keep open here) and then output the display every second. (If the output is already handled by something else and for whatever reasons shouldn't be moved here, just ignore that part.)

You'd probably still want some way of breaking out of the whole thing. Maybe an escape input:

while (true)
{
    Thread.Sleep(1000);
    DisplayCurrentStats();
    var escape = Console.Read();
    if (IsEscapeCharacter(escape))
        break;
}
OutputGoodByeMessage();

In the IsEscapeCharacter() method you can check if the character read from the Console (if there was one) matches the expected "escape" character. (The esc key seems like a standard choice, though for obscurity you can use anything else in order to try to prevent "accidental escape.") This would allow you to terminate the application cleanly if you need to.

It's still at 1-second delay increments, which isn't ideal. Though even at 1/10-second it's still spending the vast majority of its time sleeping (that is, not consuming computing resources) while providing some decent UI responsiveness (who complains about a 1/10-second delay?):

Thread.Sleep(100);

OTHER TIPS

I assume you want to run tasks on the background, and as such you should just start a thread, like this:

private static void Main(string[] args)
{
    new Thread(new ThreadStart(SomeThreadFunction)).Start();

    while(true)
    {
        Console.Read();
    }
}

static void SomeThreadFunction()
{
  while(true) {
    Console.WriteLine("Tick");
    Thread.Sleep(1000);
  }
}

I don't want my program to terminate if by mistake I press enter

You want some thing similar to this:

while (Console.ReadKey(true).Key == ConsoleKey.Enter)
{
    Console.Read();
}

The above code does not quit if you press ENTER key but it quits when you press any oteher keys.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top