I have a method that executes an Action after X seconds, code :
public void PerformCancelableAction(string name, Action action, int delay)
{
CancellationTokenSource cts = new CancellationTokenSource();
_cancellationTokens.Add(new Tuple<string, CancellationTokenSource>(name, cts));
Task.Factory.StartNew(async delegate
{
await Task.Delay(delay);
if (!cts.IsCancellationRequested)
action();
}, cts.Token).ContinueWith((prevTask) =>
{
//prevTask.Wait(); even with this
_cancellationTokens.RemoveAll(f => f.Item1 == name);
});
}
I add in a List<Tuple<string, CancellationTokenSource>>
the name of the action and its CTS, why ? So that when the user does CancelAction(name)
I look for the name in the list and I cancel with the token.
Now, the main idea is working. But, the code within the ContinueWith gets executed before the previous action was finished, logically, it has to wait for the previous action no ?
It has to wait the Task.Delay so that the user has the chance to cancel it, but right now, since the CTS is deleted from the list right away, the action cannot be canceled..
Any idea why? Thanks !