1

My console application is waiting for keypresses in the console window. The Console.ReadKey method blocks until a new key event is available. But the application can also continue due to other events like data coming from a network connection. When that happens, the application must stop listening to a key press event so that following input works properly, for example a subsequent call to Console.ReadLine. But there's still that blocking call to ReadKey and it's eating the next keypress before ReadLine is served again.

The ReadKey call is already running in a Task so I can wait for it together with other events. But the task won't end when I want it to. It will only end when the user eventually presses a key in the console window. That key may be supposed to go in the next read method.

I've tried capturing the task's current thread and calling Thread.Abort on it, but that causes ThreadAbortedExceptions to appear anywhere else. Even handling them somewhere doesn't help. Maybe it's got something to do with that the task is not 'running' but in the state of WaitingForActivation. Whatever that means. (Honestly, I didn't expect that from handling exceptions where they're not supposed to show up. Just to mention my desperate actions.)

So what can I do to abort the blocking call to the Console.ReadKey method? Reading its decompiled implementation, it calls the ReadConsoleInput native function which blocks until one event is available.

I couldn't find a way to generate or inject such an event.

How can I finally stop that biest of a function?

Side note: Using Console.KeyAvailable is not an option because it would result in busy waiting for console input. I've read somewhere along the console functions from Win API that there's some way to wait for console input events, but that's totally not covered by the managed API.

ygoe
  • 16,668
  • 21
  • 98
  • 190
  • Note in particular [this answer](https://stackoverflow.com/a/9634490/3538012) in the duplicate question, which addresses sending a key to the current process. In that answer, the key they send is the "Enter" key; you can use whatever key you want, and may find using some other key is more appropriate in your case (e.g. matches what the user would be expected to enter, and/or is more easily identifiable as coming from within the process). – Peter Duniho Jul 16 '15 at 06:43

0 Answers0