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;
}
}
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:
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 addSystem.Windows.Forms
reference):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, importingSystem.Threading
: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:
Then you can loop safely by doing something like this:
Even better, you could mix the latter two solutions by replacing the
while
iterator with aSpinWait.SpinUntil
invocation: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 .check this Console.Read
Add The
Read
method to show the output.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 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.
I always add the following statement to a console application.(Create a code snippet for this if you wish)
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.