简体   繁体   中英

System.InvalidOperationException with tasks in C#

I am trying to make my code faster by using tasks (Parallel.foreach). Here is my updated code:

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

However, it gives me this exception:

An exception of type 'System.InvalidOperationException' occurred in System.Drawing.dll but was not handled in user code Additional information: Object is currently in use elsewhere. If there is a handler for this exception, the program may be safely continued.

The exception happens on this line:

bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);

any idea of how to solve this is appreciated.

All your Tasks access to the same shared Bitmap bmpDest .

Move the definition of it to Parallel.ForEach block so that every task can use its own Bitmap..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM