有一组任务,一次只运行 X [英] Have a set of Tasks with only X running at a time
本文介绍了有一组任务,一次只运行 X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 100 个任务,这些任务需要 10 秒才能完成.现在我只想一次运行 10 个,比如当这 10 个中的 1 个完成另一个任务时,直到所有任务都完成.
Let's say I have 100 tasks that do something that takes 10 seconds. Now I want to only run 10 at a time like when 1 of those 10 finishes another task gets executed till all are finished.
现在我总是使用 ThreadPool.QueueUserWorkItem()
来完成这样的任务,但我读到这样做是不好的做法,我应该改用 Tasks.
Now I always used ThreadPool.QueueUserWorkItem()
for such task but I've read that it is bad practice to do so and that I should use Tasks instead.
我的问题是我没有找到适合我的场景的好例子,所以你能告诉我如何使用 Tasks 实现这个目标吗?
My problem is that I nowhere found a good example for my scenario so could you get me started on how to achieve this goal with Tasks?
推荐答案
SemaphoreSlim maxThread = new SemaphoreSlim(10);
for (int i = 0; i < 115; i++)
{
maxThread.Wait();
Task.Factory.StartNew(() =>
{
//Your Works
}
, TaskCreationOptions.LongRunning)
.ContinueWith( (task) => maxThread.Release() );
}
这篇关于有一组任务,一次只运行 X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文