c# - 以秒为单位限制 Task.Factory.Start 中的 Task 数量

标签 c# task

我看过很多关于限制一次任务数量的帖子(System.Threading.Tasks - Limit the number of concurrent Tasks 是一个很好的帖子)。

但是,我需要以秒为单位限制任务数量——每秒只有 X 数量的任务?有没有一种简单的方法可以做到这一点?

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

我宁愿做一些事情,比如每 1 秒/20 启动一个任务。有什么想法吗?

最佳答案

我认为,这可以作为一个起点。下面的示例创建了 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();
    }


}

关于c# - 以秒为单位限制 Task.Factory.Start 中的 Task 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771524/

相关文章:

c# - 带有嵌入式 IronPython 的 RESTful Web 服务 : engine & scope questions

c# - OpenPop 删除消息

C#的编译器设计——前向引用

linux - 从 TID 获取 PID 的预制方法

c# - 可以在 C# 应用程序中执行实时多 channel 音频卷积吗?

c# - 在循环中顺序执行函数而不阻塞ui

c# - 单元测试是否捕获到异常

project-management - 团队领导和成员可以使用哪些工具来管理任务(敏捷编程)

c# - 任务不更新WPF中的UI

visual-studio - 如何在 Visual Studio 中执行自定义文件特定命令/任务?