<分区>
我的控制台应用程序正在执行一个完全专注于用户界面的线程,它花费大量时间阻塞在 Console.ReadLine()
上(这个调用在内部深处花费时间Windows,在 .NET 框架的控制之外)。
我需要中止这个线程。但是,以下代码似乎不起作用:
this.UserInterfaceThread.Abort();
有什么想法吗? Thread.Interrupt() 有什么用吗?
更新
正如 Hans Passant 指出的那样:
The CLR imposes rather sane rules on the state of a thread when it aborts it. The perils of Thread.Abort() are well known, what certainly cannot ever work reliably is aborting a thread that's executing unmanaged code. Which is the case when you call Console.ReadLine(), the thread is buried deep inside Windows operating system code.
解决方案是简单地将 [enter] 击键插入当前正在运行的控制台应用程序,这会解除对 Console.ReadLine() 的阻塞,因此线程会立即中止。
我们不能使用 SendKeys,因为它特定于窗口窗体,而且它还需要当前窗口具有焦点。
解决方案是使用位于 inputsimulator.codeplex.com 的库它包装了 Windows SendInput() 调用。
查看示例代码:
.NET call to send [enter] keystroke into the current process, which is a console app?