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
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;