How to interrupt Console.ReadLine

后端 未结 10 813
情歌与酒
情歌与酒 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:40

    So here is a Solution working on Windows 10 and not using any fancy threading or dllimport magic. It worked fine for me I hope it helps.

    I basically create a stream reader sitting on the standard input. Reading it kinda "async" and just dispose the stream reader if I want to cancel the readline.

    Here is my Code:

        private System.IO.StreamReader stdinsr = new System.IO.StreamReader(Console.OpenStandardInput());
        [DebuggerHidden]
        private string ReadLine() {
            return stdinsr.ReadLineAsync().Result;
        }
    
        protected override void OnExit(ExitEventArgs e) {
            base.OnExit(e);
    
            commandLooper.Abort();
            stdinsr.Dispose();
        }
    

    NOTE: Yes I read async but I wait for the task result so its basically still waiting for user input.

提交回复
热议问题