InvalidOperationException - 对象当前正在其他地方使用 [英] InvalidOperationException - object is currently in use elsewhere

查看:103
本文介绍了InvalidOperationException - 对象当前正在其他地方使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了这个问题 但它没有帮助.

I've gone through this SO question but it didn't help.

这里的情况不同.我正在使用后台工作者.第一个后台工作人员开始对用户的图像输入进行操作,并且在 firstbackgroundworker_runworkercompleted() 内部我正在调用其他 3 个后台工作人员

The case here is different. I'm using Backgroundworkers. 1st backgroundworker starts operating on the image input of user and inside firstbackgroundworker_runworkercompleted() I'm using calling 3 other backgroundworkers

 algo1backgroundworker.RunWorkerAsync();
 algo2backgroundworker.RunWorkerAsync();
 algo3backgroundworker.RunWorkerAsync();

这是每个的代码:

algo1backgroundworker_DoWork()
{
 Image img = this.picturebox.Image;
 imgclone = img.clone();
 //operate on imgclone and output it
}

algo2backgroundworker_DoWork()
{
 Image img = this.picturebox.Image;
 imgclone = img.clone();
 //operate on imgclone and output it
}

类似的操作在其他algo*backgrougrondworker_doWork()中完成.

similar operations are done in other algo*backgrougrondworker_doWork().

现在有时我会收到InvalidOperationException - 对象当前正在其他地方使用".它非常随意.我有时在 algo1backgroundworker_DoWork 中得到这个,有时在 algo2backgroundworker_DoWork 中得到这个,有时在 Application.Run(new myWindowsForm());

Now SOMETIMES I'm getting "InvalidOperationException - object is currently in use elsewhere". Its very arbitrary. I somtimes get this in algo1backgroundworker_DoWork and sometimes in algo2backgroundworker_DoWork and sometimes in Application.Run(new myWindowsForm());

我不知道发生了什么.

推荐答案

GDI+ 内部有一个锁,可以防止两个线程同时访问位图.这不是阻塞类型的锁,它是程序员做错了什么,我会抛出异常"类型的锁.您的线程正在爆炸,因为您正在所有线程中克隆图像(== 访问位图).您的 UI 线程正在爆炸,因为它试图在线程克隆它的同时绘制位图(== 访问位图).

There's a lock inside GDI+ that prevents two threads from accessing a bitmap at the same time. This is not a blocking kind of lock, it is a "programmer did something wrong, I'll throw an exception" kind of lock. Your threads are bombing because you are cloning the image (== accessing a bitmap) in all threads. Your UI thread is bombing because it is trying to draw the bitmap (== accessing a bitmap) at the same time a thread is cloning it.

您需要将位图的访问权限限制为只有一个线程.在启动 BGW 之前克隆 UI 线程中的图像,每个 BGW 都需要自己的图像副本.在 RunWorkerCompleted 事件中更新 PB 的 Image 属性.这样你会失去一些并发性,但这是不可避免的.

You'll need to restrict access to the bitmap to only one thread. Clone the images in the UI thread before you start the BGWs, each BGW needs its own copy of the image. Update the PB's Image property in the RunWorkerCompleted event. You'll lose some concurrency this way but that's unavoidable.

这篇关于InvalidOperationException - 对象当前正在其他地方使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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