RandomizedHarmony

View Original

Exiting a loop with a keypress

I recently was working on a script and wanted a loop to continue until I killed it manually, but I did not want to have to press CTRL+C as that would break out of the entire script.  After digging through a little bit, I figured out that I can use the ReadKey method of [System.Console] to read in data information while the loop continued running.  Digging around on the web for something that already was doing this (why re-invent the wheel?) I came across something on Stack Overflow which had most of the framework established already.

After looking through the code, I pulled out the unnecessary portions and have a simple drop in snippet that I can now drop into any loop and have it exit when necessary.

The code for this is below

See this content in the original post

Hopefully this is helpful in some way.  While I don't see using this often - I can see some specific instances where this could be helpful - one of which is the next thing I will be writing about later this weekend.