在用于图像处理的 C# 代码中出现“对象正在使用”错误

Getting "Object in use" error in C# code for image processing

提问人:tomato bar 提问时间:11/5/2023 最后编辑:tomato bar 更新时间:11/5/2023 访问量:46

问:

我正在开发一个 C# 应用程序,在该应用程序中我正在执行图像处理,并遇到了“对象正在使用”错误的问题。下面是导致问题的代码的简化版本:

private void piccc(object s)
{
    pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    using (Graphics gfx = Graphics.FromImage(pictureBox1.Image))
    {
        ColorMatrix matrix = new ColorMatrix();
        ImageAttributes attributes = new ImageAttributes();
        foreach (Control c in flowLayoutPanel1.Controls)
        {
            if (((Label)c.Controls[0]).Text == "   ")
            {
                string[] ll3 = ((PictureBox)c.Controls[1]).Name.Split(',');
                matrix.Matrix33 = (float)int.Parse(ll3[6]) / 100;
                attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                gfx.DrawImage((Bitmap)((PictureBox)c.Controls[1]).Image, new Rectangle(int.Parse(ll3[0]), int.Parse(ll3[1]), int.Parse(ll3[11]), int.Parse(ll3[12]), int.Parse(ll3[2]), int.Parse(ll3[3]), int.Parse(ll3[4]), int.Parse(ll3[5]), GraphicsUnit.Pixel, attributes);
            }
        }
    }
}

private void pictureboxpaint()
{
    ParameterizedThreadStart param = new ParameterizedThreadStart(piccc);
    Thread thread = new Thread(param);
    thread.Start();
}

当我尝试使用单独的线程将图像绘制到 pictureBox1 上时,会出现问题。我怀疑它与对图形对象的并发访问有关,但我不确定如何解决它。有人可以提供有关如何防止“对象正在使用”错误并确保此代码中适当的线程安全的指导吗?

我将不胜感激有关该问题以及如何纠正它的任何建议或解释。谢谢!

编辑:我在这一行收到此错误:gfx.DrawImage((Bitmap)((PictureBox)c.Controls[1]).Image, new Rectangle(int.Parse(ll3[0]), int.Parse(ll3[1]), int.Parse(ll3[11]), int.Parse(ll3[12]), int.Parse(ll3[2]), int.Parse(ll3[3]), int.Parse(ll3[4]), int.Parse(ll3[5]), GraphicsUnit.Pixel, attributes);

C# .NET 多线程映像 WinForms

评论

0赞 Behtash 11/5/2023
我认为资源正在使用中,任何其他过程都将被拒绝。1-如果您使用的是多线程,请尝试锁定和解锁资源。2-我认为在这个问题中,您可以为图像定义全局变量并填充它,然后在该变量上执行任何您想要的事情。
0赞 tomato bar 11/5/2023
@Behtash如果我锁定它们,速度会比普通线程慢,而且我不能使用全局变量,因为我有 infinit 对象
0赞 Mustafa Özçetin 11/5/2023
我的建议是,不要在其他线程上执行绘图代码,而是在 UI 线程上执行。如果您有耗时的操作,如调整图像大小等,请重构您的代码,以便在另一个线程上执行计算,然后执行实际的绘图代码。
0赞 Enigmativity 11/6/2023
不能从非 UI 线程创建、访问或更新任何 UI 元素。时期。

答: 暂无答案