Reputation: 564
Suppose an application has a method name PrintAsterisk() that prints asterisks on a screen continuously. The method runs on a Task separate from the user interface. I need to ensure that the application stop printing the asterisk on screen when the user presses the Enter key.
How do I cancel a running task by pressing Enter key in console?
Below is the my method that is simplified:
static void PrintAsterisk() {
while (true) {
Thread.Sleep(1000);
Console.Write("*");
}
}
Upvotes: 2
Views: 793
Reputation: 3890
Depends on how you create a thread, you can pass CancellationToken
to it. Inside method ran in the thread just check if that token has cancellation request an break your method if so.
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(v=vs.110).aspx
Upvotes: 2