有一组任务与只适用于X同时运行 [英] Have a set of Tasks with only X running at a time

查看:150
本文介绍了有一组任务与只适用于X同时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有100个任务做一些事情,需要10秒。
现在我想只当那些10名的另一项任务,直到被执行的所有1完成像同时运行10。

现在我总是用 ThreadPool.QueueUserWorkItem()对于这样的任务,但我读过,这是不好的做法,这样做,我应该用任务来代替。

我的问题是,我无处找到了一个很好的例子,我的情况,所以你可以让我开始对如何使用任务来实现这一目标?


解决方案

  SemaphoreSlim maxThread =新SemaphoreSlim(10);的for(int i = 0; I< 115;我++)
{
    maxThread.Wait();
    Task.Factory.StartNew(()=>
        {
            //你的作品
        }
        ,TaskCreationOptions.LongRunning)
    .ContinueWith((任务)= GT; maxThread.Release());
}

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.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆