c# - 当所述线程正在执行 Console.ReadLine 时,如何中止 .NET 中的另一个线程?

标签 c# .net multithreading visual-studio-2010

<分区>

我的控制台应用程序正在执行一个完全专注于用户界面的线程,它花费大量时间阻塞在 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?

最佳答案

CLR 在中止线程时对线程的状态强加了相当合理的规则。 Thread.Abort() 的危险是众所周知的,当然不能可靠地工作的是中止正在执行非托管代码的线程。当您调用 Console.ReadLine() 时就是这种情况,线程深埋在 Windows 操作系统代码中。

您将不得不以不同的方式执行此操作。一个显而易见的方法是让这个“用户界面”线程停止程序,而不是相反。可以像“退出”命令或众所周知的“按任意键继续”消息一样简单。

或者将线程的 IsBackground 属性设置为 true。现在您不必中止它,Windows 将在您的 Main() 方法退出后关闭进程时终止它。

关于c# - 当所述线程正在执行 Console.ReadLine 时,如何中止 .NET 中的另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8984838/

相关文章:

c# - 让程序确保它有 3 个自己的实例一直在运行?

c# - Process.Start() 和进程树

c# - 如何检查 uri 字符串是否有效

java - 兼容 .Net 的 RSA key (XML 格式)

c# - 线程是否必要/有用?

java - 管理对单个数据库的多线程访问的各种方法有哪些?

ios - NSUserDefaults 线程在 IOS 上的扩展之间共享数据是否安全?

c# - 我如何使用频率分析来解析加密的段落?

c# - 如何阻止 XElement.Save 转义字符?

c# - 使用可变数量的功能