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


基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01