限制的同时执行任务的数量 [英] Limiting the number of simultaneously executing tasks

查看:148
本文介绍了限制的同时执行任务的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

认为这是一个巨大的任务池:

Consider this a huge pool of tasks:

var tasks = new Task[4]
    {
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething()),
        Task.Factory.StartNew(() => DoSomething())
    };

Task.WaitAll(tasks);



如果我只是想跑说同时3个任务?我将如何实现在代码?

What if I only wanted to run say 3 tasks simultaneously? How would I implement that in code?

推荐答案

一个不太复杂的例子比MSDN版本是使用Parallel.Invoke设置最大并行度:

A less complicated example than the MSDN version would be to use Parallel.Invoke setting the max degree of parallelism:

Parallel.Invoke(
    new ParallelOptions() { MaxDegreeOfParallelism = 3 }, 
    () => DoSomething(), 
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething(),
    () => DoSomething());



Parallel.Invoke()将阻塞,直到所有并行操作完成(即没有代码超越parallel.invoke将运行,直到他们都完成)。如果这不会为你工作,那么你将最终需要创建自己的任务调度如图所示的是MSDN文章由丹尼尔链接。

Parallel.Invoke() will however block until all parallel operations are finished (meaning that no code beyond the parallel.invoke will run until they are all completed). If this doesn't work for you then you will end up needing to create your own task scheduler as is shown is the MSDN article linked by Daniel.

这篇关于限制的同时执行任务的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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