簡體   English   中英

Parallel.ForEach重載

[英]Parallel.ForEach overloads

我想要做的是每個線程有一個本地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. 傳遞一個IEnumarable Source,它是RecordsToBeProcessed
  2. 有一個局部變量,只在Bitmap類型的線程的開頭只初始化一次。
  3. 在body中訪問本地位圖變量和記錄
  4. 最后配置Bitmap

ForEach沒有重載,它具有不在ParallelLoopState狀態對象中傳遞的初始和最終線程本地操作。 您只需要在主循環體​​中添加一個參數。 此外,您必須return身體末端的對象,以便將其傳遞給下一次迭代以重復使用。 最后在你的線程初始化器中,當你真正想要做的是在你在該函數中創建的位圖上return時,傳入bitmap變量。

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();
            });

我在上面的例子中使用了這個重載

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM