【发布时间】:2014-09-27 04:31:04
【问题描述】:
我有一个转换 JPG 文件的代码。我使用任务使其更快。它更快,但它弄乱了图像及其日期。对我来说,这就像变量在不同的线程之间共享,这使得图像中的变量用于循环中的下一个/另一个图像。有没有办法确保循环中的所有变量在当前任务/线程中都是私有的?
这是我的代码:
int intImageW, intImageH, intImageWtmp;
DateTime creationTime, lastWriteTime, lastAccessTime;
Parallel.ForEach(strarrFileList, strJPGImagePath =>
{
Bitmap bmpDest = new Bitmap(1, 1);
creationTime = File.GetCreationTime(strJPGImagePath);
lastWriteTime = File.GetLastWriteTime(strJPGImagePath);
lastAccessTime = File.GetLastAccessTime(strJPGImagePath);
using (Bitmap bmpOrig = new Bitmap(strJPGImagePath))
{
//Bitmap bmpOrig = new Bitmap(strJPGImagePath);
intImageW = bmpOrig.Width;
intImageH = bmpOrig.Height;
if ((intImageW > intImageH) && (intImageW > intLongSide))
{
intImageH = (int)((double)intImageH / ((double)intImageW / (double)intLongSide));
intImageW = intLongSide;
}
else if ((intImageH > intImageW) && (intImageH > intLongSide))
{
intImageW = (int)((double)intImageW / ((double)intImageH / (double)intLongSide));
intImageH = intLongSide;
}
else if ((intImageH == intImageW) && (intImageW > intLongSide))
{
intImageH = intLongSide;
intImageW = intLongSide;
}
else
{
// do something
}
// FIX THE ORIENTATION
if (Array.IndexOf(bmpOrig.PropertyIdList, 274) > -1)
{
var orientation = (int)bmpOrig.GetPropertyItem(274).Value[0];
switch (orientation)
{
case 1:
// No rotation required.
break;
case 2:
bmpOrig.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
bmpOrig.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
bmpOrig.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case 5:
bmpOrig.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
bmpOrig.RotateFlip(RotateFlipType.Rotate90FlipNone);
intImageWtmp = intImageW;
intImageW = intImageH;
intImageH = intImageWtmp;
break;
case 7:
bmpOrig.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
bmpOrig.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
}
bmpOrig.RemovePropertyItem(274);
}
bmpDest = new Bitmap(bmpOrig, new Size(intImageW, intImageH));
}
bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);
bmpDest.Dispose();
GC.Collect(2, GCCollectionMode.Forced);
File.SetCreationTime(strJPGImagePath, creationTime);
File.SetLastWriteTime(strJPGImagePath, lastWriteTime);
File.SetLastAccessTime(strJPGImagePath, lastAccessTime);
});
问题来自以下变量: intImageW、intImageH、intImageWtmp、creationTime、lastWriteTime 和 lastAccessTime。
【问题讨论】:
-
为什么不在范围内移动它们
-
链接为 duplicate 的问题的类似问题。