出于某种原因,我们收到“InvalidOperationException:对象当前正在其他地方使用”。
在我们的自定义 OnPaint 期间,如下(实际上几乎是一行代码的行副本......那里只有这么少)。
我们在下面的异常处理程序中登录,以检测我们是否以某种方式从非 UI 线程调用 OnPaint ......并且没有被触发,但我们正在记录该错误(参见下面的堆栈跟踪)。
在我们遇到这些错误的机器上,我们还看到了来自其他控件的可怕的红色 X(可能在他们的 OnPaints 周围没有尝试/捕捉)。
它们可能是相关的,但是如果仅从 UI 线程调用此代码,我无法弄清楚可能导致该错误的原因。
有任何想法吗?
这是堆栈跟踪:
System.InvalidOperationException:对象当前正在其他地方使用。
在 System.Drawing.Graphics.CheckErrorStatus(Int32 状态)
在 System.Drawing.Graphics.DrawRectangle(Pen pen, Int32 x, Int32 y, Int32 width, Int32 height)
在 System.Windows.Forms.ControlPaint.DrawBorderSimple(图形图形,
System.Windows.Forms.ControlPaint.DrawBorder(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style) at
MyUserControl.OnPaint(PaintEventArgs e) 的矩形边界、颜色颜色、ButtonBorderStyle 样式
这是课程:
public class MyUserControl : UserControl
{
// Override this to set your custom border color
protected Color mBorderColor = SystemColors.ControlDarkDark;
public MyeUserControl()
: base()
{
this.BorderStyle = BorderStyle.None;
this.Padding = new Padding(1);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
try
{
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, mBorderColor, ButtonBorderStyle.Solid);
}
catch (Exception ex)
{
// check if we're not on the UI thread, and if not, log it
// log exception
}
}
}