我想使用这个解决方案来调用Console.ReadLine()
超时:
delegate string ReadLineDelegate();
string ReadLine(int timeoutms)
{
string resultstr = null;
ReadLineDelegate d = Console.ReadLine;
IAsyncResult result = d.BeginInvoke(null, null);
result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs
if (result.IsCompleted)
{
resultstr = d.EndInvoke(result);
Console.WriteLine("Read: " + resultstr);
}
else
{
Console.WriteLine("Timed out!");
// Bug? resource leak? No d.EndInvoke(), which blocks until Console.ReadLine() returns
}
result.AsyncWaitHandle.Close();
return resultstr;
}
但评论者警告说:
every ReadLine you call sits there waiting for input.
If you call it 100 times, it creates 100 threads
which don't all go away until you hit Enter 100 times!
...特别是因为我想在一个永远循环中反复调用它。
我知道每个人都BeginInvoke()
需要一个EndInvoke()
但我不希望分支EndInvoke
中的阻塞调用。else
不知何故,我们需要abort
运行Console.ReadLine()
调用而不是让它运行到完成,因为它可能永远不会完成。
所以所有这些(复杂的)代码帮助我让 Console.ReadLine 在超时时返回,但不会结束 Console.ReadLine 退出或以其他方式消失。
我们如何才能使它正常工作,而不会遇到资源泄漏?
注意:我AsyncWaitHandle.Close()
按照 MS Calling Sync 异步调用的建议添加了