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

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

    Simple threading example to solve this

    Thread readKeyThread = new Thread(ReadKeyMethod);
    static ConsoleKeyInfo cki = null;
    
    void Main()
    {
        readKeyThread.Start();
        bool keyEntered = false;
        for(int ii = 0; ii < 10; ii++)
        {
            Thread.Sleep(1000);
            if(readKeyThread.ThreadState == ThreadState.Stopped)
                keyEntered = true;
        }
        if(keyEntered)
        { //do your stuff for a key entered
        }
    }
    
    void ReadKeyMethod()
    {
        cki = Console.ReadKey();
    }
    

    or a static string up top for getting an entire line.

提交回复
热议问题