c# - Task.StartOrRestartWhenPossible -


i'm attempting use .net task framework. scenario this: have task needs execute whenever properties on class change. if executing, task should bail , restart such there 1 task running @ given time. in reality, may take second stop task during time may receive multiple propertychanged events (that should trigger 1 rerun of task). , propertychanged handler cannot block.

with scenario, seems need volatile flag make previous task exit. however, don't know wait exit. @ same time, don't think can add continuewith method when thing not running. (and don't want nest continuewith multiple levels deep, i?)

is there me in task library? other recommendations have one-level-deep queue of tasks? i'm using .net 4.5.

so wanted write taskscheduler this, interface doesn't provide mechanism ensuring tasks have cancellation token , being able cancel running tasks, we'll have make due scheduler doesn't follow provided tpl model/interface.

when scheduling first cancels previous task (which won't if there no previous task or has since finished). next sets current task task isn't started until previous task ends, , in body runs given action. lock needed if there 2 calls schedule 1 cancel other, , non-cancelled version 1 assigned current.

public class singlethreadedkillpredecssorscheduler {     private task current = task.fromresult(true);     private cancellationtokensource cts = new cancellationtokensource();     private object key = new object();      public task schedule(action<cancellationtoken> action)     {         lock (key)         {             cts.cancel();             cts = new cancellationtokensource();             current = current.continuewith(t => action(cts.token), cts.token);             return current;         }     }     public task<t> schedule<t>(func<cancellationtoken, t> function)     {         lock (key)         {             cts.cancel();             cts = new cancellationtokensource();             var next = current.continuewith(t => function(cts.token), cts.token);             current = next;             return next;         }     } } 

Comments