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

后端 未结 30 2603
耶瑟儿~
耶瑟儿~ 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条回答
  •  -上瘾入骨i
    2020-11-22 06:00

    If you're in the Main() method, you can't use await, so you'll have to use Task.WaitAny():

    var task = Task.Factory.StartNew(Console.ReadLine);
    var result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(5)) == 0
        ? task.Result : string.Empty;
    

    However, C# 7.1 introduces the possiblity to create an async Main() method, so it's better to use the Task.WhenAny() version whenever you have that option:

    var task = Task.Factory.StartNew(Console.ReadLine);
    var completedTask = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5)));
    var result = object.ReferenceEquals(task, completedTask) ? task.Result : string.Empty;
    

提交回复
热议问题