3

In my XNA game, I've got the game window and the console which is running a threaded Console.ReadLine() so the game doesn't hang while waiting for scripting input. I'm trying to get it where when the game window closes, the Console closes automatically, as well as the input to actually work (with the ability to print things out whilst waiting on input). I've gotten it to close automatically now by using code from this question: How to add a Timeout to Console.ReadLine()?

However, when I press enter to the input, an ObjectDisposedException is thrown. Also, I'm stuck with using a timeout when I'd rather the thing be instant. How would I go about fixing this?

public class ConsoleInput
{
    public bool running = true;

    public void Run()
    {
        String input;
        while (running)
        {
            input = ReadLine(500);
            //stuff
        }
    }

    string ReadLine(int timeoutms)
    {
        ReadLineDelegate d = Console.ReadLine;
        IAsyncResult result = d.BeginInvoke(null, null);
        result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs
        if (result.IsCompleted)
        {
            string resultstr = d.EndInvoke(result);
            Console.WriteLine("Read: " + resultstr);
            return resultstr;
        }
        result.AsyncWaitHandle.Dispose();
        return "";
    }

    delegate string ReadLineDelegate();
}

Which is called by:

LuaInput = new ConsoleInput();
LuaInputThread = new Thread(new ThreadStart(LuaInput.Run));
LuaInputThread.Start();

Thanks!

Community
  • 1
  • 1
pajm
  • 1,788
  • 6
  • 24
  • 30
  • Sure, you disposed the wait handle. Don't. Not calling the EndInvoke() method is a pretty unfriendly resource leak that lasts for 10 minutes. Okay if you don't do this often. – Hans Passant Nov 30 '11 at 20:39

1 Answers1

1

Have you tried setting the thread's

IsBackground = true; ? This will force it closed and will not allow the thread to block.