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.
Task.Run
Then you just need to launch this method inside of a Task so it can run asynchronously.
Vikram
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
John Anderson
This is great, well done.