development

왜 콘솔 창이 닫히면 즉시 출력이 표시됩니까?

big-blog 2020. 6. 10. 07:52
반응형

왜 콘솔 창이 닫히면 즉시 출력이 표시됩니까?


MSDN 의 가이드를 따라 C #을 공부하고 있습니다.

이제 방금 예제 1 ( 여기MSDN 링크)을 시도했는데 문제가 발생했습니다. 콘솔 창이 닫히면 출력이 표시되는 이유는 무엇입니까?

using System;

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

여기서 문제는 Hello World Program이 표시되고 즉시 닫힙니다.
왜 그런 겁니까?

끝났 으니까 콘솔 응용 프로그램의 실행이 완료되고 main메소드 에서 돌아 오면 관련 콘솔 창이 자동으로 닫힙니다. 이것은 예상 된 동작입니다.

디버깅 목적으로 열어 두려면 앱을 종료하고 창을 닫기 전에 컴퓨터가 키를 누를 때까지 기다리도록 지시해야합니다.

Console.ReadLine방법 은 한 가지 방법입니다. 이 줄을 코드 끝에 추가하면 ( return명령문 바로 앞 ) 종료하기 전에 응용 프로그램에서 키를 누를 때까지 기다립니다.

또는 Visual Studio 환경에서 Ctrl+ F5눌러 디버거를 연결하지 않고 응용 프로그램을 시작할 수 는 있지만 응용 프로그램을 작성할 때 원하는 디버깅 기능을 사용하지 못하게하는 명백한 단점이 있습니다.

가장 좋은 Console.ReadLine방법은 응용 프로그램을 전 처리기 지시어로 감싸서 디버깅 할 때만 메서드 를 호출하는 것입니다 . 다음과 같은 것 :

#if DEBUG
    Console.WriteLine("Press enter to close...");
    Console.ReadLine();
#endif

포착되지 않은 예외가 발생한 경우에도 창을 열어두기를 원할 수도 있습니다. 당신은 넣을 수 그렇게하려면 Console.ReadLine();A의 finally블록 :

#if DEBUG
    try
    {
        //...
    }
    finally
    {
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
#endif

사용하는 대신

Console.Readline()
Console.Read()
Console.ReadKey()

Ctrl+를 사용하여 프로그램을 실행할 수 있습니다 F5(Visual Studio에있는 경우). 그런 다음 Visual Studio는 키를 누를 때까지 콘솔 창을 열어 둡니다.

참고 :이 방법에서는 코드를 디버깅 할 수 없습니다.


CtrlF5또는에 대해 동일하게 동작합니다 F5. Main분석법 종료 직전에 놓으십시오 .

using System.Diagnostics;

private static void Main(string[] args) {

  DoWork();

  if (Debugger.IsAttached) {
    Console.WriteLine("Press any key to continue . . .");
    Console.ReadLine();
  }
}

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.


The program immediately closes because there's nothing stopping it from closing. Insert a breakpoint at return 0; or add Console.Read(); before return 0; to prevent the program from closing.


Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.


Another way is to use Debugger.Break() before returning from Main method


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);

The code is finished, to continue you need to add this:

Console.ReadLine();

or

Console.Read();

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


Add The Read method to show the output.

Console.WriteLine("Hello, World!");
Console.Read();
return 0;

I'm a little bit late to the party, but: in Visual Studio 2019 for .NET Core projects the console doesn't close automatically by default. You can configure the behaviour through menu Tools → Options → Debugging → General → Automatically close the console when debugging stops. If you get your console window automatically closing, check if the mentioned setting is not set.

The same applies to the .NET Framework new style console projects:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net472</TargetFramework>
  </PropertyGroup>

</Project>

The old style .NET Framework project still unconditionally close the console at the end (as of Visual Studio 16.0.1).

Reference: https://devblogs.microsoft.com/dotnet/net-core-tooling-update-for-visual-studio-2019-preview-2/


Here is a way to do it without involving Console:

var endlessTask = new TaskCompletionSource<bool>().Task;
endlessTask.Wait();

The program is closing as soon as it's execution is complete. In this case when you return 0;. This is expected functionality. If you want to see the output then either run it in a terminal manually or set a wait at the end of the program so that it will stay open for a few seconds ( using the threading library ).


this is the answer async at console app in C#?

anything whereever in the console app never use await but instead use theAsyncMethod().GetAwaiter().GetResult();,

example

var result = await HttpClientInstance.SendAsync(message);

becomes

var result = HttpClientInstance.SendAsync(message).GetAwaiter().GetResult();


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);


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.


To simplify what others are saying: Use Console.ReadKey();.

This makes it so the program is waiting on the user to press a normal key on the keyboard

Source: I use it in my programs for console applications.


You can solve it very simple way just invoking the input. However, if you press Enter then the console will disapper again. Simply use this Console.ReadLine(); or Console.Read();


Add the following before the return 0:

system("PAUSE");  

This prints a line to hit a key to close the window. It will keep the window up until you hit the enter key. I have my students add it to all their programs.


According to my concern, if we want to stable the OUTPUT OF CONSOLE APPLICATION, till the close of output display USE, the label: after the MainMethod, and goto label; before end of the program

In the Program.

eg:

static void Main(string[] args)
{
    label:

    // Snippet of code

    goto label;
}

참고URL : https://stackoverflow.com/questions/8868338/why-is-the-console-window-closing-immediately-once-displayed-my-output

반응형