How to create an annulable task loop?

Is it possible to use System.Threading.Task.Task to create a task loop that can be undone?

The thread should start with Task.Delay (x ms), then continue with the task specified by the user, then another Task.Delay (y ms) and repeat from the task specified by the user.

var result = Task.Delay(initialDelay)
              .ContinueWith(t => dostuff..)
              .ContinueWith what goes here?

Is it possible to complete tasks?

I could expand the timer and end it, but using the task seems to be the right way, if I need to cancel, no?

+4
source share
1 answer

await makes it very simple:

public async Task TimedLoop(Action action, 
    CancellationToken token, TimeSpan delay)
{
    while (true)
    {
        token.ThrowIfCancellationRequested();
        action();
        await Task.Delay(delay, token);
    }
}

async ( TPL) . , , Task. , , . await Timer.

public Task TimedLoop(Action action,
    CancellationToken token, TimeSpan delay)
{
    //You can omit these two lines if you want the method to be void.
    var tcs = new TaskCompletionSource<bool>();
    token.Register(() => tcs.SetCanceled());

    Task previous = Task.FromResult(true);
    Action<Task> continuation = null;
    continuation = t =>
    {
        previous = previous.ContinueWith(t2 => action(), token)
            .ContinueWith(t2 => Task.Delay(delay, token), token)
            .Unwrap()
            .ContinueWith(t2 => previous.ContinueWith(continuation, token));
    };
    previous.ContinueWith(continuation, token);
    return tcs.Task;
}
+9

Source: https://habr.com/ru/post/1529035/


All Articles