我正在尝试优化像素值读取器(来自图像)并尝试将 Parallel.For 与 Background Worker 一起使用以在条形图上显示进度。我使用字典来存储要用于其他处理的读取值。当我只使用 Parallel.For 时,它可以完美运行,而且时间不到一分钟。当我使用 Background Worker 和 Parallel.For 时,我在尝试将值添加到字典时收到空异常消息。
我正在使用 C# .Net 4。
public Dictionary<string, DNValuesSrcTrgt> ReadPixelValuesFromImages(
string _trgtRasterName,
string _trgtRasterDirectory,
string _srcRasterName,
string _srcRasterDirectory
)
{
Dictionary<string, DNValuesSrcTrgt> dictSrcTrgtImgValue = null;
IRaster2 trgtRasterData2 = null;
IRaster2 srcRasterData2 = null;
try
{
//Open both the target and source images are IRaster2 QI
trgtRasterData2 = OpenIRaster2(_trgtRasterName, _trgtRasterDirectory);
if (trgtRasterData2 == null)
{
return null;
}
srcRasterData2 = OpenIRaster2(_srcRasterName, _srcRasterDirectory);
if (srcRasterData2 == null)
{
return null;
}
dictSrcTrgtImgValue = new Dictionary<string, DNValuesSrcTrgt>();
//Create a Raster Layer class to get the Number of columns and rows
//This is read from the target Raster Image
IRasterLayer trgtRasterLyr = new RasterLayerClass();
trgtRasterLyr.CreateFromDataset(trgtRasterData2.RasterDataset);
//Loop through all the rows and column for Target Image and get the
//Cell value and the X and Y value
//Then use the X and Y value to get the Cell value from Source Image
double xCord = 0.0;
double yCord = 0.0;
object valTrgt = null;
object valSrc = null;
int cnt = 0;
string errorMessage = string.Empty;
int i = 0;
Parallel.For(0, trgtRasterLyr.ColumnCount, (j, loopstate) =>
{
//if (UserAborted) return;
for (int k = 0; k < trgtRasterLyr.RowCount; k++)
{
DNValuesSrcTrgt srcTrgtImgValue = new DNValuesSrcTrgt();
cnt++;
srcTrgtImgValue.columnID = j;
srcTrgtImgValue.rowID = k;
valTrgt = trgtRasterData2.GetPixelValue(i, j, k);
//Math.Round(Convert.ToDouble(val1), 5);
trgtRasterData2.PixelToMap(j, k, out xCord, out yCord);
int colSrc = srcRasterData2.ToPixelColumn(xCord);
int rowSrc = srcRasterData2.ToPixelRow(yCord);
valSrc = srcRasterData2.GetPixelValue(i, colSrc, rowSrc);
srcTrgtImgValue.xCord = xCord;
srcTrgtImgValue.yCord = yCord;
srcTrgtImgValue.DNImageTrgt = Math.Round(Convert.ToDouble(valTrgt), 5);
srcTrgtImgValue.DNImageSrc = Math.Round(Convert.ToDouble(valSrc), 5);
//**This is where Error is Occuring**
dictSrcTrgtImgValue.Add(j.ToString() + "," + k.ToString(), srcTrgtImgValue);
valTrgt = null;
valSrc = null;
}
});
}
catch (Exception ex)
{
dictSrcTrgtImgValue = null;
System.Diagnostics.Debug.WriteLine(ex.Message);
return null;
}
finally
{
GC.Collect();
}
return dictSrcTrgtImgValue;
}