C# C中任务的System.InvalidOperationException#

C# C中任务的System.InvalidOperationException#,c#,parallel-processing,task,C#,Parallel Processing,Task,我试图通过使用tasks(Parallel.foreach)来加快代码的速度。这是我的更新代码: int intImageW, intImageH; Bitmap bmpDest = new Bitmap(1, 1); DateTime creationTime, lastWriteTime, lastAccessTime; Parallel.ForEach(strarrFileList, strJPGImagePath => { creationTime = File.Ge

我试图通过使用tasks(Parallel.foreach)来加快代码的速度。这是我的更新代码:

int intImageW, intImageH;
Bitmap bmpDest = new Bitmap(1, 1);
DateTime creationTime, lastWriteTime, lastAccessTime;

Parallel.ForEach(strarrFileList, strJPGImagePath =>
{
      creationTime = File.GetCreationTime(strJPGImagePath);
      lastWriteTime = File.GetLastWriteTime(strJPGImagePath);
      lastAccessTime = File.GetLastAccessTime(strJPGImagePath);

      using (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
             mSplash("This photo (" + Path.GetFileName(strJPGImagePath) + ") is smaller than the desired size!");

         bmpDest = new Bitmap(bmpOrig, new Size(intImageW, intImageH));
      }
      bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);

      File.SetCreationTime(strJPGImagePath, creationTime);
      File.SetLastWriteTime(strJPGImagePath, lastWriteTime);
      File.SetLastAccessTime(strJPGImagePath, lastAccessTime);
});
但是,它给了我一个例外:

System.Drawing.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理 其他信息:对象当前正在其他地方使用。 如果存在此异常的处理程序,则程序可以安全地继续

此行出现异常:

bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);
任何关于如何解决此问题的想法都将受到欢迎。

您的所有任务都可以访问相同的共享位图
bmpDest

将其定义移动到
Parallel.ForEach
块,以便每个任务都可以使用自己的位图

Parallel.ForEach(strarrFileList, strJPGImagePath =>
{
     Bitmap bmpDest = new Bitmap(1, 1);
     ........
});

当你发现自己用一个无意义的对象初始化一个变量时,比如
新位图(1,1)
想想:一定有更好的方法。谢谢,但是我应该在哪里处理它呢?目前我在循环后处理它。@M0HS3N保存它,然后再处理它。