0

I'm trying to create a console app with a thread but when I try to close the thread the Console.ReadLine() blocks it. Do you know how to abort a Console.ReadLine() or how to close a thread immediately? Here's my code:

public static void commandHandling()
{
    while (Globals.running) // Globals is just a class where I have all of my global vars
    {
        string command = Console.ReadLine();
        switch (command)
        {
            default:
                Console.WriteLine("The command '" + command + "' cannot be found.");
                break;
            case "exit":
                Main.Stop(); // Main is here the "control center" of the app
                break;
        }
    }
}

Here starts the Thread: Globals.cmdThread = new Thread(new ThreadStart(commandHandling)); Globals.cmdThread.Start();

Morga121
  • 3
  • 6
  • Does this help? http://stackoverflow.com/questions/14131608/how-to-terminate-a-thread-in-c `Thread.Abort` – Steve Drake Apr 28 '15 at 16:02
  • 1
    Can you show the code where you start your thread? The code you've shown looks like you're trying to terminate the whole application (I'm assuming `Main` is a class you've defined). – Craig W. Apr 28 '15 at 16:05
  • 5
    Always try very, very hard to exit from a thread cleanly. All kinds of state can get corrupted if you abort it. You may want to look into non-blocking I/O. I have a hunch that you only want to close the thread on process exit, though -- in which case, just mark it as a "Background" thread! – Cameron Apr 28 '15 at 16:05
  • Thanks, Steve but it does not – Morga121 Apr 28 '15 at 16:21
  • 1
    Please elaborate on what you are _actually_ trying to do. This seems like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). It seems to me that you should not really need to interrupt the `Console.ReadLine()` method. Instead, your console I/O should be independent of whatever else it is you are trying to do (and subsequently, trying to abort). If all the thread is doing is waiting for input, _why do you need to abort it_? What is the point? – Peter Duniho Apr 28 '15 at 16:31
  • [Does this help?](http://stackoverflow.com/q/5620603/265419) – James Apr 28 '15 at 16:53
  • Okay ,the code that I posted is a debug console for a game using sfml.net, and when the game quits,it would be awkward if it would've leave a console winow, but at the same time I need it to debug the game. – Morga121 Apr 28 '15 at 18:20

0 Answers0