How to interrupt Console.ReadLine

后端 未结 10 784
情歌与酒
情歌与酒 2020-11-28 11:34

Is it possible to stop the Console.ReadLine() programmatically?

I have a console application: the much of the logic runs on a different thread and in th

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 11:39

    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: 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);
        }
    }
    

提交回复
热议问题