我看过很多关于限制一次任务数量的帖子(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/