0

i have a Recurring Cancellable Task launcher taken from this question:

How to create a thread/Task with a continuous loop?

public static class TaskHelper
{
    public static class RecurrentCancellableTask
    {
        public static Task StartNew(
            Action action,
            TimeSpan pollInterval,
            CancellationToken token,
            TaskScheduler scheduler = null,
            TaskCreationOptions taskCreationOptions = TaskCreationOptions.LongRunning
            )
        {
            if (scheduler == null) scheduler = TaskScheduler.Default;
            return Task.Factory.StartNew(
                () =>
                {
                    while (true)
                        try
                        {
                            action();
                            if (token.WaitHandle.WaitOne(pollInterval)) break;
                        }
                        catch
                        {
                            return;
                        }
                }, token, taskCreationOptions, scheduler);
        }
    }
}

everything works like a charm. however now i need to put this task launcher inside a loop and launch x job:

 foreach (var job in collection)
                    {
                        TaskHelper.RecurrentCancellableTask.StartNew(() => { somecode(job); }, TimeSpan.FromMilliseconds(i), token);
                    }

the collection loop is started every n seconds if a job from collection has been removed, the job must be stopped.

if a job from collection has been added, the job must run every i milliseconds.

if a job from collection is alredy running every i milliseconds must be ignored and cannot be started another one.

jobs can be launched parallely.

how i can manage this situation? is there any task manager pattern where i can look?

Thanks!

D

AeonDave
  • 781
  • 1
  • 8
  • 17

0 Answers0