如何中断Console.ReadLine [英] How to interrupt Console.ReadLine

查看:188
本文介绍了如何中断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.

我该如何实现?

推荐答案

更新:此技术在Windows 10上不再可靠.请不要使用它.
实施上的重大改动在Win10中使控制台的行为更像终端.毫无疑问,将有助于新的Linux子系统.一个(意外的?)副作用是CloseHandle()会死锁直到读取完成,从而使该方法无效.我会保留原始帖子,只是因为它可能可以帮助别人找到替代方案.

UPDATE: this technique is no longer reliable on Windows 10. Don't use it please.
Fairly heavy implementation changes in Win10 to make a console act more like a terminal. No doubt to assist in the new Linux sub-system. One (unintended?) side-effect is that CloseHandle() deadlocks until a read is completed, killing this approach dead. I'll leave the original post in place, only because it might help somebody to find an alternative.

UPDATE2:看看wischi的答案,这是一个不错的选择.

UPDATE2: Look at wischi's answer for a decent alternative.

有可能,您必须通过关闭stdin流来拉动地板垫.该程序演示了这个想法:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆