This one’s kind of specific, but sometimes when you’re writing a console app that does a lot of asynchronous stuff, and you want to cancel it at any time by pressing escape.
However, Console.ReadKey is blocking… so that’s not super great.
CancellationToken
First, make use of the cancellation tokens. I’ve talked about them before, but they allow you to cancel in-flight asynchronous operations. Essentially, we will want to create our own asynchronous task that waits for a key press and then cancels the cancellation token, thereby stopping whatever kind of asynchronous processes you have running.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void MonitorKeypress(CancellationToken cancellationToken) | |
{ | |
ConsoleKeyInfo cki = new ConsoleKeyInfo(); | |
do | |
{ | |
// true hides the pressed character from the console | |
cki = Console.ReadKey(true); | |
// Wait for an ESC | |
} while (cki.Key != ConsoleKey.Escape); | |
// Cancel the token | |
cancellationToken.Cancel(); | |
} |
Task.Run
Then you just need to launch this method inside of a Task so it can run asynchronously.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Launch the task to wait for a keypress | |
Task consoleKeyTask = Task.Run(() => { MonitorKeypress(); }); | |
// ... Launch other async tasks ... | |
// Waits for the keypress to end it all | |
await consoleKeyTask; |
Good article, read more about async await in C# MVC
https://qawithexperts.com/article/c-sharp/async-await-keyword-in-c-explained-with-console-application/214
This is great, well done.