How to keep console window open

2019-01-06 21:41发布

When I run my program, the console window seems to run and close. How to keep it open so I can see the results?

class Program
{
    public class StringAddString       
    {                        
        public virtual void AddString()
        {
            var strings2 = new string[] { "1", "2", "3", "4", "5","6", "7", "8", "9"};

            Console.WriteLine(strings2);
            Console.ReadLine();
        }
    }

    static void Main(string[] args)
    {          
        StringAddString s = new StringAddString();            
    }
}

9条回答
祖国的老花朵
2楼-- · 2019-01-06 22:20

You can handle this without requiring a user input.

Step 1. Create a ManualRestEvent at the start of Main thread

ManualResetEvent manualResetEvent = new ManualResetEvent(false);

Step 2 . Wait ManualResetEvent

manualResetEvent.WaitOne();

Step 3.To Stop

manualResetEvent.Set();
查看更多
乱世女痞
3楼-- · 2019-01-06 22:32

There are two ways I know of

1) Console.ReadLine() at the end of the program. Disadvantage, you have to change your code and have to remember to take it out

2) Run outside of the debugger CONTROL-F5 this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)

查看更多
SAY GOODBYE
4楼-- · 2019-01-06 22:34

Use Console.Readline() at the end .Your code will not close until you close it manually.Since Readline waits for input that needs to be entered for your code hence your console will be open until you type some input.

查看更多
男人必须洒脱
5楼-- · 2019-01-06 22:34

Make sure to useConsole.ReadLine(); to keep the preceeding Console.WriteLine(""); message from closing.

查看更多
Emotional °昔
6楼-- · 2019-01-06 22:35

Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key

static void Main(string[] args)
{
    StringAddString s = new StringAddString();
    Console.Read();            
}
查看更多
太酷不给撩
7楼-- · 2019-01-06 22:35

If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:

if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();

Like other answers have stated, the call to Console.ReadLine() will keep the window open until enter is pressed, but Console.ReadLine() will only be called if the debugger is attached.

查看更多
登录 后发表回答