Jump to content

At the end of your main method you can do a Console.ReadKey() (pretty sure that's the right method) so when the end of the main is reached you press a key and it closes. On the other hand if you have an indefinitely running loop or something in the main so that the end of the main method is never reached then you could in theory attach a listener to look for any key press and close your program that way, terminating any connections it has open then exiting.

Link to post
Share on other sites

At the end of your main method you can do a Console.ReadKey() (pretty sure that's the right method) so when the end of the main is reached you press a key and it closes. On the other hand if you have an indefinitely running loop or something in the main so that the end of the main method is never reached then you could in theory attach a listener to look for any key press and close your program that way, terminating any connections it has open then exiting.

i heave an infinite loop in the main.

Link to post
Share on other sites

i heave an infinite loop in the main.

Then use break when a key is pressed.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

Another option to consider is to utilize the cancel key event. This runs when "Ctrl + c" is pressed and is a common way to exit console apps when they are running.

 

Here's an example, some more examples and explanation can be found here.

class Program{    private static readonly ManualResetEvent QuitEvent = new ManualResetEvent(false);    static void Main(String[] args)    {        Console.CancelKeyPress += (sender, eArgs) =>        {            QuitEvent.Set();            eArgs.Cancel = true;        };        MainStart();        QuitEvent.WaitOne();        MainStop();    }    private static void MainStart()    {        Console.WriteLine("Starting...");        // Start running your code    }    private static void MainStop()    {        Console.WriteLine("Stopping...");        // Do anything you need to before the application finishes    }}
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×