gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:06:39 24 4
gpt4 key购买 nike

<分区>

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com