在我的XNA游戏中,我有游戏窗口和控制台,其中控制台正在运行一个线程化的Console.ReadLine(),以便在等待脚本输入时游戏不会挂起。我试图让当游戏窗口关闭时,控制台自动关闭,并且输入实际上能够工作(并具有在等待输入时打印输出的能力)。
现在我已经使用了来自这个问题的代码使其自动关闭:如何向Console.ReadLine()添加超时?
但是,当我按下回车键进行输入时,会抛出ObjectDisposedException异常。此外,我被困在使用超时的情况下,而我更希望这个过程是即时的。我该如何解决这个问题?
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();
}
这被称为:
LuaInput = new ConsoleInput();
LuaInputThread = new Thread(new ThreadStart(LuaInput.Run));
LuaInputThread.Start();
谢谢!