I have a background long running method which uses cancellation token. On cancel, the thread still keeps processing even after the method called on CancellationTokensource.Token.Register is invoked.
Is there a way to stop processing the thread after register is invoked?
CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
void HandleBackgroundTasks(object args)
{
var task = Task.Factory.StartNew(() => BackgroundTask(),
_cancellationTokensource.Token);
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
//handle faulted
}
}
}
void BackgroundTask()
{
_cancellationTokenSource.Token.Register(() =>
{
service.CancelTask();//method to reset database values on cancel
}
//Some code to check whether to run HandleLongrunningTask method
service.HandleLongrunningTask(); //long running task
}