How to add a Timeout to Console.ReadLine()?

后端 未结 30 2561
耶瑟儿~
耶瑟儿~ 2020-11-22 04:57

I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:56

    Ended up here because a duplicate question was asked. I came up with the following solution which looks straightforward. I am sure it has some drawbacks I missed.

    static void Main(string[] args)
    {
        Console.WriteLine("Hit q to continue or wait 10 seconds.");
    
        Task task = Task.Factory.StartNew(() => loop());
    
        Console.WriteLine("Started waiting");
        task.Wait(10000);
        Console.WriteLine("Stopped waiting");
    }
    
    static void loop()
    {
        while (true)
        {
            if ('q' == Console.ReadKey().KeyChar) break;
        }
    }
    

提交回复
热议问题