Why is the console window closing immediately once

2018-12-31 15:04发布

I'm studying C# by following the guides in MSDN.

Now, I just tried the Example 1 (here is the link to MSDN), and I've encountered an issue: why is the console window closing immediately once displayed my output?

using System;

public class Hello1
{
    public static int Main()
    {
        Console.WriteLine("Hello, World!");
        return 0;
    }
}

19条回答
旧时光的记忆
2楼-- · 2018-12-31 15:28

If you want to keep your application opened, you have to do something in order to keep its process alive. The below is the simplest example, to put at the end of your program:

while (true) ;

However, it'll cause the CPU to overload, as it's therefore forced to iterate infinitely.

At this point, you can opt to use System.Windows.Forms.Application class (but it requires to add System.Windows.Forms reference):

Application.Run();

This not leaks CPU and works successfully.

In order to avoid to add System.Windows.Forms reference, you can use a simple trick, the so-called spin waiting, importing System.Threading:

SpinWait.SpinUntil(() => false);

This also works perfectly, and it mainly consists in a while iterator with a negated condition that is returned by the above lambda method. Why isn't this overloading CPU? You can look at the source code here; anyway, it basically waits some cycle of the processor to keep instructions running.

You can also opt for creating a message looper, which peeks the pending messages and processes each of them before passing to the next iteration:

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "PeekMessage")]
public static extern int PeekMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "GetMessage")]
public static extern int GetMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "TranslateMessage")]
public static extern int TranslateMessage(ref NativeMessage lpMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "DispatchMessage")]
public static extern int DispatchMessage(ref NativeMessage lpMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode]
public static bool ProcessMessageOnce()
{
    NativeMessage message = new NativeMessage();
    if (!IsMessagePending(out message))
        return true;
    if (GetMessage(out message, IntPtr.Zero, 0, 0) == -1)
        return true;
    Message frameworkMessage = new Message()
    {
        HWnd = message.handle,
        LParam = message.lParam,
        WParam = message.wParam,
        Msg = (int)message.msg
    };
    if (Application.FilterMessage(ref frameworkMessage))
        return true;
    TranslateMessage(ref message);
    DispatchMessage(ref message);
    return false;
}

Then you can loop safely by doing something like this:

while (true)
    ProcessMessageOnce();

Even better, you could mix the latter two solutions by replacing the while iterator with a SpinWait.SpinUntil invocation:

SpinWait.SpinUntil(ProcessMessageOnce);
查看更多
泛滥B
3楼-- · 2018-12-31 15:29

Use Console.Read(); to prevent the program from closing, but make sure you add the Console.Read(); code before return statement, or else it will be a unreachable code .

    Console.Read(); 
    return 0; 

check this Console.Read

查看更多
皆成旧梦
4楼-- · 2018-12-31 15:29

Add The Read method to show the output.

Console.WriteLine("Hello, World!");
Console.Read();
return 0;
查看更多
皆成旧梦
5楼-- · 2018-12-31 15:30

if your program requires you to press enter to continue like you have to enter a value and continue, then add a new double or int and type write before retunr(0); scanf_s("%lf",&the variable);

查看更多
像晚风撩人
6楼-- · 2018-12-31 15:31

I assume the reason you don't want it to close in Debug mode, is because you want to look at the values of variables etc. So it's probably best to just insert a break-point on the closing "}" of the main function. If you don't need to debug, then Ctrl-F5 is the best option.

查看更多
看风景的人
7楼-- · 2018-12-31 15:34

I always add the following statement to a console application.(Create a code snippet for this if you wish)

Console.WriteLine("Press any key to quit!");
Console.ReadKey();

Doing this helps when you want to experiment different concepts through console application.

Ctr + F5 will make the Console stay but you cant debug! All the console applications that I have written in realworld is always non-interactive and triggered by a Scheduler such as TWS or CA Work station and did not require something like this.

查看更多
登录 后发表回答