是否可以通过编程方式停止 Console.ReadLine()
?
Is it possible to stop the Console.ReadLine()
programmatically?
我有一个控制台应用程序:大部分逻辑在不同的线程上运行,在主线程中我使用 Console.ReadLine()
接受输入.当分离的线程停止运行时,我想停止从控制台读取.
I have a console application: the much of the logic runs on a different thread and in the main thread I accept input using Console.ReadLine()
. I'd like to stop reading from console when the separated thread stop running.
我怎样才能做到这一点?
How can I achieve this?
更新:此技术在 Windows 10 上不再可靠.请不要使用它.
相当大的实现更改在 Win10 中使控制台更像终端.毫无疑问,协助新的 Linux 子系统.一个(意外?)副作用是 CloseHandle() 死锁直到读取完成,从而使这种方法死亡.我将保留原来的帖子,只是因为它可能帮助某人找到替代品.
UPDATE2:查看 wischi 的答案,寻找一个不错的选择.
UPDATE2: Look at wischi's answer for a decent alternative.
有可能,您必须通过关闭标准输入流来猛拉地垫.这个程序演示了这个想法:
It's possible, you have to jerk the floor mat by closing the stdin stream. This program demonstrates the idea:
using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
ThreadPool.QueueUserWorkItem((o) => {
Thread.Sleep(1000);
IntPtr stdin = GetStdHandle(StdHandle.Stdin);
CloseHandle(stdin);
});
Console.ReadLine();
}
// 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);
}
}
这篇关于如何中断 Console.ReadLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!