Limit the number of tasks in Task.Factory.Start per second

I saw several messages about limiting the number of tasks at a time ( System.Threading.Tasks - Limit the number of simultaneous tasks to one).

However, I need to limit the number of tasks to the second - only X the number of tasks per second? Is there an easy way to do this?

I was thinking of creating a ConcurrentDictionary, the key is the current second, and the second is the score. Performing a check if we are within 20 seconds and then stop. It seems suboptimal.

I would rather do something like completing a task every 1 s / 20. Any thoughts?

+3
source share
1 answer

, . 50 ( 5 /).

, . , , Task.Delay((int)shouldWait).Wait() QueueTask

TaskFactory taskFactory = new TaskFactory(new TimeLimitedTaskScheduler(5));

for (int i = 0; i < 50; i++)
{
    var x = taskFactory.StartNew<int>(() => DateTime.Now.Second)
                        .ContinueWith(t => Console.WriteLine(t.Result));
}

Console.WriteLine("End of Loop");

public class TimeLimitedTaskScheduler : TaskScheduler
{
    int _TaskCount = 0;
    Stopwatch _Sw = null;
    int _MaxTasksPerSecond;

    public TimeLimitedTaskScheduler(int maxTasksPerSecond)
    {
        _MaxTasksPerSecond = maxTasksPerSecond;
    }

    protected override void QueueTask(Task task)
    {
        if (_TaskCount == 0) _Sw = Stopwatch.StartNew();

        var shouldWait = (1000 / _MaxTasksPerSecond) * _TaskCount - _Sw.ElapsedMilliseconds;

        if (shouldWait < 0)
        {
            shouldWait = _TaskCount = 0;
            _Sw.Restart();
        }

        Task.Delay((int)shouldWait)
            .ContinueWith(t => ThreadPool.QueueUserWorkItem((_) => base.TryExecuteTask(task)));

        _TaskCount++;
    }

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
    {
        return base.TryExecuteTask(task);
    }

    protected override IEnumerable<Task> GetScheduledTasks()
    {
        throw new NotImplementedException();
    }


}
+3

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


All Articles