更改C#的Parallel.For循环的增量值 [英] Changing the incremental value of a C# Parallel.For loop

查看:902
本文介绍了更改C#的Parallel.For循环的增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个for循环它由2递增每次迭代器传递到并行对于使用TPL循环。该数据不依赖于顺序或以任何方式受限,但我只想来处理我的源阵列(这是_Datalist在下面的代码)的所有其他元素的数据,因此需要由2递增。

I want to convert a for loop which increments the iterator by 2 every pass into a Parallel For loop using the TPL. The data is not order dependent or constrained in any way, but I only want to process the data in every other element of my source array (which is _Datalist in the code below), hence the need to increment by 2.

我的循环:

for (int i = 1; i < _DataList.Length - 1; i += 2)
{
     // Do work for _DataList[i]
}

是否可以告诉并行循环,我想用两个而不是一个递增我?

Is it possible to tell the parallel loop that I want to increment i by two instead of one?

下面是并行$ b;

        Task.Factory.StartNew(() =>
            Parallel.For(1, _DataList.Length, i =>
            {
                // do work for _DataList[i]                    
            })
        );



我可以告诉内环身体无视我的奇数值,但似乎痘痘乱 - ?有没有在环路初始化莫名其妙地做这件事的方法

I could tell the inner loop body to ignore odd values of i, but that seems a litle messy - is there a way of doing it in the loop initialisation somehow?

推荐答案

如何:

var odds = Enumerable.Range(1, _DataList.Length).Where(i => i % 2 != 0);

Task.Factory.StartNew(() =>
    Parallel.ForEach(odds, i =>
    {
        // do work for _DataList[i]                    
    })
);

这篇关于更改C#的Parallel.For循环的增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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