C# 增强并行运算能力#
我有8个逻辑处理器。当执行以下代码时C# 增强并行运算能力#,c#,parallel-processing,task,parallel.foreach,parallel.for,C#,Parallel Processing,Task,Parallel.foreach,Parallel.for,我有8个逻辑处理器。当执行以下代码时 public void test() { Parallel.For( 1, 1001, i => { IntensiveWork(i); }); } private static void IntensiveWork(int i) { Random r=new Random(); Thread.Sleep(r.Next(i*1)); } 我注意到Parall
public void test()
{
Parallel.For( 1, 1001, i => { IntensiveWork(i); });
}
private static void IntensiveWork(int i)
{
Random r=new Random();
Thread.Sleep(r.Next(i*1));
}
我注意到Parallel.For可以生成多批8个作业。每批将按顺序执行。问题在于,如果该批中有7/8个作业已完成,则下一批将继续等待最后一个作业完成。这意味着7个核心将不繁忙。有没有更好的方法来实现并行性是C#,在C#中,一旦批处理中的一个作业完成,它将为该核心分配另一个作业 您可以将多个任务从单个队列中读取
static void test()
{
ConcurrentQueue<int> queue = new ConcurrentQueue<int>(Enumerable.Range(1, 1000));
int taskCount = Environment.ProcessorCount;
Task[] tasks = new Task[taskCount];
for (int taskIndex = 0; taskIndex < taskCount; taskIndex++)
{
Task task = Task.Factory.StartNew(() => IntensiveWorkTask(queue));
tasks[taskIndex] = task;
}
Task.WaitAll(tasks);
}
private static void IntensiveWorkTask(ConcurrentQueue<int> queue)
{
while (queue.TryDequeue(out int value))
IntensiveWork(value);
}
private static void IntensiveWork(int i)
{
Random r = new Random();
Thread.Sleep(r.Next(i * 1));
}
static void test()
{
ConcurrentQueue=新的ConcurrentQueue(Enumerable.Range(11000));
int taskCount=Environment.ProcessorCount;
Task[]tasks=新任务[taskCount];
对于(int taskIndex=0;taskIndexIntensiveWorkTask(queue));
任务[任务索引]=任务;
}
Task.WaitAll(任务);
}
私有静态无效密集工作任务(ConcurrentQueue队列)
{
while(queue.TryDequeue(out int value))
密集工作(价值);
}
私人静态空洞密集工作(int i)
{
随机r=新随机();
睡眠(r.Next(i*1));
}
试试微软的反应式框架(又称Rx)——只需NuGetSystem.Reactive
,然后使用System.Reactive.Linq添加代码>-然后您可以执行以下操作:
public void test()
{
IObservable<Unit> query =
Observable
.Range(1, 1000)
.SelectMany(i =>
Observable
.Start(() => IntensiveWork(i)));
IDisposable subscription = query.Subscribe();
}
private static Random r = new Random();
private static void IntensiveWork(int i)
{
Thread.Sleep(r.Next(i * 1));
}
公共无效测试()
{
可观测查询=
可观察
.范围(11000)
.SelectMany(i=>
可观察
.开始(()=>密集工作(i));
IDisposable subscription=query.subscripte();
}
私有静态随机r=新随机();
私人静态空洞密集工作(int i)
{
睡眠(r.Next(i*1));
}
使用.Subscribe(…
可以在每个工作项完成时对其做出响应。如果使用Parallel.ForEach(Enumerable.Range(11000),i=>{IntensiveWork(i);}),会发生什么
?上的Microsoft文档非常广泛。特别是链接的电子书是一本有趣的读物,它还解释了分区的工作原理。另请参阅。