Created
November 7, 2017 15:00
-
-
Save romipetrelis/e3cab64cdd53e54ca136cda8e5c4e654 to your computer and use it in GitHub Desktop.
console app with cancel-able infinite loop
This file contains 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
// credit: https://stackoverflow.com/questions/35714547/c-sharp-console-application-run-for-loop-while-not-disturbing-rest-of-exec | |
class Program { | |
static void Main(string[] args){ | |
var tokenSource = new CancellationTokenSource(); | |
var cancellationToken = tokenSource.Token; | |
var backgroundTask = Task.Run(() => | |
{ | |
Console.WriteLine("Background task started"); | |
long count = 0; | |
while (!cancellationToken.IsCancellationRequested) | |
{ | |
//TODO: do your thing | |
count++; | |
} | |
Console.WriteLine("task cancelled"); | |
return count; | |
}, cancellationToken); | |
Console.WriteLine("Back in main"); | |
Console.ReadKey(); | |
tokenSource.Cancel(); | |
Console.WriteLine("Counter: {0}", backgroundTask.Result); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment