加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在.NET中中止另一个线程,当所述线程正在执行Console.R

发布时间:2020-12-15 17:44:13 所属栏目:百科 来源:网络整理
导读:我的控制台应用程序正在执行一个完全用于用户界面的线程,它在Console.ReadLine()上花费了大量的时间阻止(这个调用花费在 Windows的大部分时间内,在.NET的控制之外)框架). 我需要中止这个线程.但是,以下代码似乎不起作用: this.UserInterfaceThread.Abort();
我的控制台应用程序正在执行一个完全用于用户界面的线程,它在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,因为这是特定于Windows窗体,它还要求当前窗口具有焦点.

解决方案是使用打包Windows SendInput()调用的inputsimulator.codeplex.com的库.

参见示例代码:

.NET call to send [enter] keystroke into the current process,which is a console app?

解决方法

使用SendKeys并模拟ENTER键.获得帮助 here.

祝你好运.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读