ConsoleApp Freeze user input for 1sec [Answered]
I need to freeze user input for 1 second after the last user input.
What i use for the input in a do while loop is this:
input = Console.ReadKey(true);
Then I call the method:
public void timeout(){
Stopwatch sw = new Stopwatch();
Random random = new Random();
var ranNum = random.Next(650, 950);
sw.Start(); while (true) { if (sw.Elapsed.TotalMilliseconds > ranNum) { break; } } sw.Stop(); } Problem is that it still reads user input while the timout is happening. System thread freeze also do not work. Please advice!
sw.Start(); while (true) { if (sw.Elapsed.TotalMilliseconds > ranNum) { break; } } sw.Stop(); } Problem is that it still reads user input while the timout is happening. System thread freeze also do not work. Please advice!
22 Replies
the input is buffered, so during that delay u need to consume the input and just immediately discard it.
Gonna try it out
Why not
Thread.Sleep
?Thread sleep only freezes the app. The input stays buffered after that time passes
Sure, not disagreeing with you there
You can just consume it all at the end of the delay though?
u wouldnt be able to differentiate which input was within the time of the
Thread.Sleep()
call and which would be afterwardsAs I'm trying to overwrite the input of the user it still doesnt work
Right, so you consume everthing at the end of the sleep, and everything after that point happened after the delay...
how do u know if its everything?
Console.ReadKey()
is blocking. so even if the user would press the key after 10 seconds it would be discardedWhat do you mean with consume?
Console.ReadKey()
basically consumes -> is read from the bufferConsole readkey doesnt really help, because it awaits user input even tho it is not saved to a variable
I still need to press backspace afterwards which is also a key
This almost works, but it still forces me to make a random click so the loop will break
while (sw.Elapsed.TotalMilliseconds <= 1000)
{
input = Console.ReadKey(true);
if (sw.Elapsed.TotalMilliseconds < 1000) break;
}
could it be that u write some kind of console game?
Just call
Console.Read
in a loop until it returns -1?
Thread.Sleep(1000); while (Console.Read() != -1) { }
?oh wow, i totally missed that method, yeah thats the way to go i guess
Or you can read straight from
Console.OpenStandardInput
in one go?while (sw.Elapsed.TotalMilliseconds <= 1000)
{
Console.Read();
if (sw.Elapsed.TotalMilliseconds < 1000) break;
}
This one works!
Thank you
Thanks to you also! 🙂
*cap5lut
thx, and sorry for the confusion, and use canton7's way, much less cpu load ;p
its /close
/close
, accept the suggestion✅ This post has been marked as answered!