Created
November 19, 2017 20:13
-
-
Save luisdeol/79b19590f3a6398ce527dcfda77eca28 to your computer and use it in GitHub Desktop.
Using ContinueWith and Cancellation of a Task
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
| namespace manage_multithreading | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); | |
| CancellationToken token = cancellationTokenSource.Token; | |
| int theCount = 0; | |
| Console.WriteLine("Task running...Count from 0 to..."); | |
| Console.WriteLine("Press ENTER to interrupt the execution!"); | |
| Task theIncredibleTask = Task.Run(() => | |
| { | |
| while (!token.IsCancellationRequested) | |
| { | |
| Thread.Sleep(1000); | |
| Console.WriteLine(theCount.ToString()); | |
| theCount++; | |
| } | |
| }, token) | |
| .ContinueWith(task => | |
| { | |
| Console.WriteLine("You just cancelled the theIncredibleTask task! :("); | |
| }, TaskContinuationOptions.OnlyOnRanToCompletion); | |
| Console.ReadLine(); | |
| cancellationTokenSource.Cancel(); | |
| try | |
| { | |
| theIncredibleTask.Wait(token); | |
| } | |
| catch (OperationCanceledException exception) | |
| { | |
| Console.WriteLine("The end!"); | |
| } | |
| Console.ReadLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment