我有一个 C# 桌面应用程序,其中我创建了一个线程,不断从一个源(实际上是一个数字相机)获取图像,并将其放在 GUI 中的一个面板上(panel.Image = img),此面板必须是另一个线程,因为它是控件的代码后端。
该应用程序可以正常工作,但在某些机器上,我会在随机时间间隔(不可预测)收到以下错误:
************** Exception Text **************
System.InvalidOperationException: The object is currently in use elsewhere.
然后面板变成了一个红十字,红色X - 我想这是可以从属性中编辑的无效图片图标。应用程序继续工作,但面板永远不会更新。据我所知,这个错误来自控件的onpaint事件,在那里我在图片上画了其他东西。
我尝试在那里使用锁定,但没有运气 :(
我调用将图像放在面板上的函数的方式如下:
if (this.ReceivedFrame != null)
{
Delegate[] clients = this.ReceivedFrame.GetInvocationList();
foreach (Delegate del in clients)
{
try
{
del.DynamicInvoke(new object[] { this,
new StreamEventArgs(frame)} );
}
catch { }
}
}
这是委托:
public delegate void ReceivedFrameEventHandler(object sender, StreamEventArgs e);
public event ReceivedFrameEventHandler ReceivedFrame;
以下是控件代码后台中函数如何注册到它的方法:
Camera.ReceivedFrame +=
new Camera.ReceivedFrameEventHandler(camera_ReceivedFrame);
我也尝试了
del.Method.Invoke(del.Target, new object[] { this, new StreamEventArgs(b) });
而不是
del.DynamicInvoke(new object[] { this, new StreamEventArgs(frame) });
但是没有运气
有人知道我如何修复这个错误或者至少如何捕获错误并让线程再次将图像放在面板上吗?
LockBits()
,然后在中间进行渲染,最后再调用UnlockBits()
会发生什么。 - Dmitri Nesteruk