Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Last active June 1, 2019 08:56
Show Gist options
  • Save aliabidzaidi/ec9cda9db9e8a699f9b9d85849832acf to your computer and use it in GitHub Desktop.
Save aliabidzaidi/ec9cda9db9e8a699f9b9d85849832acf to your computer and use it in GitHub Desktop.
Different ways to Monitor a Canceled task in TPL
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