开发者

Alternative to Console.ReadLine() to keep the Console visible

开发者 https://www.devze.com 2023-01-17 15:24 出处:网络
Isn\'t there a better looking statement (or way) to keep the console from disappearing than the hackish Console.ReadLine() call. Something that\'s more expressive of开发者_如何学Pythonthe purpose of,

Isn't there a better looking statement (or way) to keep the console from disappearing than the hackish Console.ReadLine() call. Something that's more expressive of开发者_如何学Python the purpose of, more orthogonal to, keeping the Console visible ?


If you are still developing application you can run via Ctrl + F5 (Without debugging) otherwise you can use Console.ReadKey() (same but there is no more option)


You can do:

Console.ReadKey();

Console.ReadLine() is not really hackish, your pausing the screen to wait for input. The input can either be a single key, or a string.

Update

One nice thing about the ReadKey() method is that it "waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed." MSDN

This is different than ReadLine which takes in a string. Arguably, cleaner.


It depends on the context. If you're talking about running a command line, debugging through your code, and then being able to view the results on the console you have two options:

  1. If you run with the debugger attached (f5), you must use Console.ReadLine
  2. If you run without the debugger attached (ctrl + f5), it will stay open ... but then you obviously can't debug through.

I'm not sure why that's the default behavior, but there it is :-)


I usually use one of these:

Console.ReadKey(true); //You might want to put this in an infinite loop
new AutoResetEvent(false).WaitOne();

In VS You can also run (Ctrl + F5) the program (in distinction to running in debug) and it will add a system pause after it finishes executing.

I'd say that WaitOne, and just running (& not debugging) the program are your non-hackish options.

If you do want to debug, perhaps set a breakpoint at the last }.


Depends on what I am doing. If I am doing multi-threaded work and want my Console application to remain alive until all other work is done, I usually do something like this. (Similar to MasterMastic)

using System;
using System.Threading;

namespace Test_Console
{
    class Program
    {
        static EventWaitHandle EWHandle;

        static void Main(string[] args)
        {
            EWHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
            Thread WorkThread = new Thread(new ThreadStart(DoStuff));
            EWHandle.WaitOne();
        }

        static void DoStuff()
        {
            Console.WriteLine("Do what you want here");

            EWHandle.Set();
        }
    }
}

Of course, there's always just using the regular breakpoints and the other debugging tools if that's what you're going for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号