我想做的是每个线程都有一个本地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();
});
对于第三个参数应该是我初始化局部变量的地方我得到它不需要一个参数,但我认为我做错了,我似乎无法找到正确的重载。
我想做的是
RecordsToBeProcessed
答案 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