+-
c#-限制Task.Factory.Task中的任务数
我看到了很多关于一次限制任务数量的帖子( System.Threading.Tasks – Limit the number of concurrent Tasks是一个不错的选择).

但是,我需要按秒限制任务数-每秒仅X个任务数?有没有简单的方法可以做到这一点?

我考虑过要创建一个ConcurrentDictionary,键是当前秒数,而第二个是到目前为止的计数.检查当前秒数是否为20,然后停止.这似乎不是最理想的.

我宁愿做一些像每1s / 20加速一个任务的事情.有什么想法吗?

最佳答案
我认为,这可以作为起点.下面的示例创建50个任务(每秒运行5个任务).

这不会阻止创建任务的代码.如果要在所有任务都已调度之前阻止调用者,则可以在QueueTask中使用Task.Delay((int)shouldWait).Wait()

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();
    }


}
点击查看更多相关文章

转载注明原文:c#-限制Task.Factory.Task中的任务数 - 乐贴网