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
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 appsorry 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
console key input is not really suited for multi-threaded applications
I guess you could have a
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 threadsManualResetEventSlim Class (System.Threading)
Represents a thread synchronization event that, when signaled, must be reset manually. This class is a lightweight alternative to ManualResetEvent.
also I'm not sure how readkey would work across threads
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)
how are you exiting the program then?
do you just crash it? seems not ideal
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
as long as you can Ctrl+C-it...
yup i can do that
I still think using a manual reset event is a more clean solution, but if this works for you...
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
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.