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

后端 未结 30 2566
耶瑟儿~
耶瑟儿~ 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:44

    Im my case this work fine:

    public static ManualResetEvent evtToWait = new ManualResetEvent(false);
    
    private static void ReadDataFromConsole( object state )
    {
        Console.WriteLine("Enter \"x\" to exit or wait for 5 seconds.");
    
        while (Console.ReadKey().KeyChar != 'x')
        {
            Console.Out.WriteLine("");
            Console.Out.WriteLine("Enter again!");
        }
    
        evtToWait.Set();
    }
    
    static void Main(string[] args)
    {
            Thread status = new Thread(ReadDataFromConsole);
            status.Start();
    
            evtToWait = new ManualResetEvent(false);
    
            evtToWait.WaitOne(5000); // wait for evtToWait.Set() or timeOut
    
            status.Abort(); // exit anyway
            return;
    }
    

提交回复
热议问题