How to use use ReadKey in a Task when i'm using ReadKey elsewhere to stop the program from exiting?

I start a Task and then use Console.ReadKey to stop the program from exiting. I want to use ReadKey again in the Task but the first key it reads is from the first Console.ReadKey that I use to stop the program from exiting....Does anyone know a solution to this?
13 Replies
Anu6is
Anu6is2y ago
you can check for a specific key (esc for example) before exiting the application alternately, you could also use the generic host builder to run the app
Limited Past
Limited Past2y ago
sorry i don't think my problem was clear...the problem is that when i press a key for input, it's the first ReadKey that reads it (the one which i don't care about because its just to stop it from exiting) essentially, the ReadKey i'm using to stop program execution and exiting is blocking any other ReadKeys im using until that one is read
Susko3
Susko32y ago
console key input is not really suited for multi-threaded applications I guess you could have a
while (true) {}
while (true) {}
instead of readkey to prevent exiting or like a global static manual reset event that you would Wait() on in the main thead, and signal in other threads
Susko3
Susko32y ago
ManualResetEventSlim Class (System.Threading)
Represents a thread synchronization event that, when signaled, must be reset manually. This class is a lightweight alternative to ManualResetEvent.
Susko3
Susko32y ago
also I'm not sure how readkey would work across threads
Limited Past
Limited Past2y ago
thank you, i'll have a look in to that i solved this by replacing ReadKey (the one used to block exiting the program) with await Task.Delay(-1)
Susko3
Susko32y ago
how are you exiting the program then? do you just crash it? seems not ideal
Limited Past
Limited Past2y ago
the program will be running 24/7 so im not too fussed with exiting probably not the most ideal solution lol, but it works for me for what i need at least
Susko3
Susko32y ago
as long as you can Ctrl+C-it...
Limited Past
Limited Past2y ago
yup i can do that
Susko3
Susko32y ago
I still think using a manual reset event is a more clean solution, but if this works for you...
Limited Past
Limited Past2y ago
thanks i will look in to that again in the future, for now i just needed a quick fix to continue working on it haha
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.