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

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

    I may be reading too much into the question, but I am assuming the wait would be similar to the boot menu where it waits 15 seconds unless you press a key. You could either use (1) a blocking function or (2) you could use a thread, an event, and a timer. The event would act as a 'continue' and would block until either the timer expired or a key was pressed.

    Pseudo-code for (1) would be:

    // Get configurable wait time
    TimeSpan waitTime = TimeSpan.FromSeconds(15.0);
    int configWaitTimeSec;
    if (int.TryParse(ConfigManager.AppSetting["DefaultWaitTime"], out configWaitTimeSec))
        waitTime = TimeSpan.FromSeconds(configWaitTimeSec);
    
    bool keyPressed = false;
    DateTime expireTime = DateTime.Now + waitTime;
    
    // Timer and key processor
    ConsoleKeyInfo cki;
    // EDIT: adding a missing ! below
    while (!keyPressed && (DateTime.Now < expireTime))
    {
        if (Console.KeyAvailable)
        {
            cki = Console.ReadKey(true);
            // TODO: Process key
            keyPressed = true;
        }
        Thread.Sleep(10);
    }
    

提交回复
热议问题