我正在尝试创建一个多线程程序,从一个图片框中获取某个位图,每个线程分析并更改其中的一部分,然后将其保存回图片框.我已经使用了一个lock()来处理共享位图对象和图片框的指令,但由于某种原因,我仍然每6-10次运行得到"对象目前在其他地方使用"错误.
private Object locker = new Object();
void doThread(Bitmap bmp2) //simplified - other references not important
{
//some code here
//....
lock (locker)
{
Graphics gr = Graphics.FromImage(bmp2); //this is where i get the errors, they're related to bmp2
gr.DrawImage(bmp, new Rectangle(0, 0, 800, 600));
gr.Dispose();
pictureBox1.Image = bmp2;
}
}
void runThreads()
{
Bitmap bmp2 = new Bitmap(pictureBox1.Image);
Thread thread1 = new Thread(delegate() { doThread(bmp2); });
Thread thread2 = new Thread(delegate() { doThread(bmp2); });
Thread thread3 = new Thread(delegate() …Run Code Online (Sandbox Code Playgroud)