Parallel.ForEach重载

时间:2014-02-08 02:55:21

标签: c#

我想做的是每个线程都有一个本地Bitmap变量并在主体完成执行后处理它,我尝试了以下

Parallel.ForEach<Models.Record, Bitmap>
                (RecordsToBeProcessed,
                new ParallelOptions() { MaxDegreeOfParallelism = coreCount * 2 },
                (bitmap) =>
                {
                    //initalize the bitmap variable
                    lock (SourceBitmap)
                    {
                        bitmap = SourceBitmap.Clone();
                    }
                },
                (record, bitmap) =>
                {
                    //the body 
                }
                ,
                (bitmap) =>
                {  //finally dispose the local thread bitmap variable
                    bitmap.Dispose();
                });

对于第三个参数应该是我初始化局部变量的地方我得到它不需要一个参数,但我认为我做错了,我似乎无法找到正确的重载。

我想做的是

  1. 传递RecordsToBeProcessed
  2. 的IEnumarable Source
  3. 有一个局部变量,只在开始时被初始化一次 Bitmap类型的线程。
  4. 在正文中访问本地位图变量和记录
  5. 最后处理Bitmap

1 个答案:

答案 0 :(得分:2)

没有ForEach的重载,它具有初始和最终线程本地操作,不会传递到ParallelLoopState状态对象。您只需要在主循环体​​中添加一个参数。此外,您必须return身体末端的物体,以便它可以传递到下一次迭代以重复使用。最后在你的线程初始化器中,当你真正想要做的是在你在该函数中创建的位图上执行bitmap时传入return变量。

Parallel.ForEach<Models.Record, Bitmap>
            (RecordsToBeProcessed,
            new ParallelOptions() { MaxDegreeOfParallelism = coreCount * 2 },
            () => //No object is passed in here, we want to retun a new Bitmap, not pass in one.
            {
                //initalize the bitmap variable
                lock (Sourcebitmap)
                {
                    return SourceBitmap.Clone(); //You return the object you created for the thread local use.
                }
            },
            (record, loopState, bitmap) => //loopState is new, but you don't need to use the variable in the body at all.
            {
                //the body

                return bitmap; //The return is new, the object you pass in here will be the input object on the next itteration that uses the same thread (or be passed to the final function)
            }
            ,
            (bitmap) =>
            {  //finally dispose the local thread bitmap variable
                bitmap.Dispose();
            });

我在上面的例子中使用了this overload