System.InvalidOperationException,带有C#中的任务 [英] System.InvalidOperationException with tasks in C#

查看:134
本文介绍了System.InvalidOperationException,带有C#中的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用任务(Parallel.foreach)使我的代码更快.这是我更新的代码:

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:

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

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.

此行发生异常:

bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);

任何解决此问题的想法都将受到赞赏.

any idea of how to solve this is appreciated.

推荐答案

您的所有 Tasks 访问同一共享位图bmpDest.

All your Tasks access to the same shared Bitmap bmpDest.

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

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

这篇关于System.InvalidOperationException,带有C#中的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆