Yan*_*hof 8 c# task-parallel-library
我有一些包含Action(System.Action)的ConcurrentQueue.需要运行此队列中的每个操作(需要使用invoke调用).
当队列不为空时=>需要调用动作=>但是我想对将要运行的并行任务的数量进行一些限制.除此之外,可以随时向队列添加新动作.
怎么做 ?
(使用.net 4.0)
我写了一些东西,但我不确定这是最好的方法
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() );
}
}
Run Code Online (Sandbox Code Playgroud)
Ser*_*kiy 14
查看MSDN文章如何:创建限制并发的任务计划程序.你可以使用LimitedConcurrencyLevelTaskScheduler它的实现来使你的代码像这样:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4363 次 |
| 最近记录: |