如何限制通过并行任务库运行的活动任务的数量? [英] How to limit the number of active Tasks running via the Parallel Task Library?

查看:30
本文介绍了如何限制通过并行任务库运行的活动任务的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含 Action ( System.Action ) 的 ConcurrentQueue .这个队列中的每个动作都需要运行(需要使用 invoke 调用).

I have some ConcurrentQueue that contain Action ( System.Action ). Each action in this queue need to run ( need to be called by using invoke ).

当队列不为空时 => 需要调用操作 => 但我想对将运行的并行任务的数量进行一些限制.除此之外,可以随时将新操作添加到队列中.

When the queue is not empty => the action need to be invoke => But i want to make some limit on the number of the parallel task that will run. Beside this, A new action can be added to the queue any time.

怎么做?

(使用 .net 4.0)

( using .net 4.0 )

我写了一些东西,但我不确定这是最好的方法

I wrote something but i not sure this is the best approach

 SemaphoreSlim maxThread = new SemaphoreSlim(5);

 while( !actionQueue.IsEmpty )
        {
            maxThread.Wait();
            Task.Factory.StartNew( () =>
            {
                Action action;
                if( actionExecution.TryDequeue( out action) )
                {
                    action.Invoke();
                }
            },
            TaskCreationOptions.LongRunning ).ContinueWith( ( task ) => maxThread.Release() );
        }
    }

推荐答案

查看 MSDN 文章 如何到:创建一个限制并发的任务计划程序.你可以使用 LimitedConcurrencyLevelTask​​Scheduler 实现来让你的代码像这样:

Take a look on MSDN article How to: Create a Task Scheduler That Limits Concurrency. You can use LimitedConcurrencyLevelTaskScheduler implementation from it to make your code like this:

var scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
TaskFactory factory = new TaskFactory(scheduler);

while( !actionQueue.IsEmpty )
{
    factory.StartNew( () =>
    {
        Action action;
        if(actionExecution.TryDequeue(out action))                
            action.Invoke();

    }, TaskCreationOptions.LongRunning);
}

这篇关于如何限制通过并行任务库运行的活动任务的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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