How to interrupt Console.ReadLine(如何中断 Console.ReadLine)
问题描述
是否可以通过编程方式停止 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何中断 Console.ReadLine


- 在 C# 中异步处理项目队列 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01