Bitmap.Save"对象是目前在其他地方使用"线程问题线程、其他地方、对象、是目前

2023-09-05 23:28:37 作者:抱不住太阳的深海

我有一些code是这样的:

I have some code like this:

    public void SaveImage(int Counter)
    {
        var task = Task.Factory.StartNew(() =>
        {
            var image = FinalImage;
            if (image != null)
            {
                image.Save(FinalImageSaveLocation + "test" + Counter + ".bmp");
            }
        }, TaskCreationOptions.PreferFairness);
    }

我有一个for循环创建使用类似如下code图像的X量:

I have a for loop creating x amount of images using similar code below:

for(int i = 0; i < 100; i++)
{
  Pencil.DrawImage(image, x, y); //Pencil is created at a initialisation stage
  SaveImage(i);                  //by Pencil = Graphics.FromImage(FinalImage);
}

我想通过把SaveImage方法作为一项任务,这将加快速度,但我认为我得到的例外是因为循环的下一次迭代正试图绘制到最终图像的对象,而保存正在发生。我想我可以用一个锁,但我担心会慢下来?

I thought by putting the SaveImage method as a task this would speed things up but I assume I'm getting the exception is because the next iteration of the loop is trying to draw to the final image object whilst the Save is occurring. I guess I could use a lock but I fear that would slow things down?

有没有一个固定或者我应该只是删除任务?

Is there a fix or should I just remove the task?

推荐答案

事实上,你不能访问从多个线程的图像同时放。你必须做一些同步。如果性能是一个问题,您可以执行以下伎俩:

Indeed, you can't access an image from multiple threads simultaniously. You have to do some synchronization. if performance is a problem, you can perform the following trick:

在你的保存方法,获取图像上的锁。保存到存储流,解除锁定并最终保存到磁盘。 (因为磁盘IO速度很慢)。

In your save method, get a lock on the image. Save to a memory stream, release the lock and finally save to the disk. (since disk IO is very slow).

锁定部分只有有用的实际需要同步时。由于位图是不是线程安全的,你不应该使用多线程摆在首位访问它,因此,因此同步不应该是一个问题。

The lock part is only usefull when needing actual synchronization. Since a Bitmap is not thread safe, you should not access it using multiple threads in the first place and hence, therefore synchronization shouldn't be a problem.