How to interrupt Console.ReadLine

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

    I was also looking for a way to stop reading from console in certain conditions. the solution i came up with was to make a non blocking version of read line with these two methods.

    static IEnumerator> AsyncConsoleInput()
    {
        var e = loop(); e.MoveNext(); return e;
        IEnumerator> loop()
        {
            while (true) yield return Task.Run(() => Console.ReadLine());
        }
    }
    
    static Task ReadLine(this IEnumerator> console)
    {
        if (console.Current.IsCompleted) console.MoveNext();
        return console.Current;
    }
    

    this allows us to have ReadLine on separate thread and we can wait for it or use it in other places conditionally.

    var console = AsyncConsoleInput();
    
    var task = Task.Run(() =>
    {
         // your task on separate thread
    });
    
    if (Task.WaitAny(console.ReadLine(), task) == 0) // if ReadLine finished first
    {
        task.Wait();
        var x = console.Current.Result; // last user input (await instead of Result in async method)
    }
    else // task finished first 
    {
        var x = console.ReadLine(); // this wont issue another read line because user did not input anything yet. 
    }
    

提交回复
热议问题