I'm trying to create a handy extension method to Action to basically run that action after a delay: So far my extension looks like this
public static void DelayAction(this Action DelayedAction, int millisecondDelay, CancellationToken Token)
{
Task t = Task.Factory.StartNew(() => { Thread.Sleep(millisecondDelay); }, Token, TaskCreationOptions.None, TaskScheduler.Default);
t.ContinueWith(_ => DelayedAction, Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
I have a function I call that in turn uses these extensions
private void DelayTask(Action ActiontoDelay, int millisecondDelay)
{
ActiontoDelay.DelayAction(millisecondDelay, _TokenSource.Token);
}
Which I call like this:
DelayTask(() => { _SomeFunction(SomeArgs); }, 1500);
But it all seems to drop down a whole and the action never fires. Where am I going wrong?
Edit 17-11-11 2300hrs:
I removed the generic extension method as it's not relevant to this example.
Also posting comment here as it doesn't format the code clearly in comments
If instead of the call
DelayTask(() => { _SomeFunction(SomeArgs); }, 1500);
I do this directly:
Task t = Task.Factory.StartNew(() => { Thread.Sleep(1500); }, Token, TaskCreationOptions.None, TaskScheduler.Default);
t.ContinueWith(() => { _SomeFunction(SomeArgs); }, Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
It works ok (sorry if there's any syntax error there I have done it from memory) So I beleive my issue is in the handling of the Action which Nick Butler's Answer eludes to
Your continuations are returning the DelayedAction
delegate, not invoking it:
t.ContinueWith(_ => DelayedAction(), Token, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With