以下程序在“Console.ReadKey()”处抛出错误。
如何在禁用控制台后重新启用控制台?
如何在禁用控制台后重新启用控制台?
using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem((o) =>
{
Thread.Sleep(1000);
IntPtr stdin = GetStdHandle(StdHandle.Stdin);
CloseHandle(stdin);
});
Console.ReadLine();
Console.Write("ReadLine() successfully aborted by background thread.\n");
Console.Write("[any key to exit]");
Console.ReadKey(); // Throws an exception "Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read."
}
// P/Invoke:
private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(StdHandle std);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hdl);
}
}
专家额外提示
如果您想知道如何在C#中终止运行ReadLine()的后台线程,这似乎是唯一的方法(thread.Abort无法工作,因为ReadLine()在操作系统的深处以非托管代码运行)。关于此话题在StackOverflow上有很多讨论,但没有人真正发现(或发布)一个令人满意的Console.ReadLine()终止方法。我认为这段代码是正确的轨迹 - 只要我们可以在禁用控制台后重新启用它。