Last active
June 1, 2019 08:56
-
-
Save aliabidzaidi/ec9cda9db9e8a699f9b9d85849832acf to your computer and use it in GitHub Desktop.
Different ways to Monitor a Canceled task in TPL
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
CancellationTokenSource cancelSource = new CancellationTokenSource(); | |
CancellationToken cancelToken = cancelSource.Token; | |
//1 Monitoring Cancellation with polling | |
Task T1 = new Task(() => | |
{ | |
for (int i = 0; i < int.MaxValue; i++) | |
{ | |
if (token.IsCancellationRequested) { | |
// tidy up and release resources | |
throw new OperationCanceledException(cancelToken); | |
} | |
else { | |
// do a unit of work | |
} | |
//To simplify you can also use the following if you don't have resources to release | |
//cancelToken.ThrowIfCancellationRequested(); | |
Console.Write(i + "."); | |
} | |
}, cancelToken); | |
//2 Use a Delegate to Monitor which will be called when tasks get cancelled | |
cancelToken.Register(() => | |
{ | |
Console.WriteLine("Task Cancelled... *Do Something with Delegate*"); | |
}); | |
//3 Using a Wait Handle to Monitor a task | |
Task waitingTask = new Task(() => | |
{ | |
Console.WriteLine(">>>Waiting for Task to be Cancelled *WaitHandle"); | |
cancelToken.WaitHandle.WaitOne(); | |
Console.WriteLine(">>>Wait Handle Released"); | |
}); | |
//Part where you start the task and cancel it using its cancellation source | |
T1.Start(); | |
waitingTask.Start(); | |
Console.ReadKey(); | |
cancelSource.Cancel(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment