I have a long running calculation that is dependant on an input value. If the input value is changed while the calculation is running, the current calculation should be canceled and a new calculation started after the previous one has completed.
The basic idea is as follows:
Task _latestTask = Task.CompletedTask;
CancellationTokenSource _cancellationTokenSource;
int Value
{
get => _value;
set
{
_value = value;
UpdateCalculation();
}
}
void UpdateCalculation()
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = _cancellationTokenSource.Token;
var newTask = new Task(() => DoCalculation(Value, cancellationToken));
_latestTask.ContinueWith(antecedent => newTask.Start(), cancellationToken);
_latestTask = newTask;
}
However, I am finding that depending on how often Value
is set, it's possible that the continuation task is cancelled before the new task is started. The whole chain of tasks stop.
How should I organize things so that the changed value causes the current calculation to be abandoned and a new calculation started once I know the previous task has completed?