出於某種原因,我們正在獲取「InvalidOperationException:Object目前正在其他地方使用。」「InvalidOperationException:對象目前正在其他地方使用」在無害的onpaint?
在我們的定製OnPaint,下面(這實際上幾乎是一行代碼的行副本......那裏有那麼少)。
我們已經登錄了下面的異常處理程序來檢測我們是否以某種方式從非UI線程調用了OnPaint ...並且沒有被觸發,但是我們得到了該錯誤記錄(請參閱下面的堆棧跟蹤)。
在我們遇到這些錯誤的機器上,我們也看到了來自其他控件(它們的OnPaints周圍沒有try/catch)的可怕的Red X。
他們可能是相關的,但我不明白什麼可能會導致該錯誤,如果此代碼只從UI線程調用。
任何想法?
這是堆棧跟蹤:
System.InvalidOperationException:對象正在使用 別處。
在System.Drawing.Graphics.CheckErrorStatus(的Int32 狀態)
在System.Drawing.Graphics.DrawRectangle(筆筆,的Int32 的x,的Int32 Y,的Int32寬度,高度的Int32)
在 System.Windows.Forms.ControlPaint .DrawBorderSimple(圖形圖像, 矩形範圍,Colour彩色,ButtonBorderStyle風格)
在 System.Windows.Forms.ControlPaint.DrawBorder(圖形圖像, 矩形範圍,Colour彩色,ButtonBorderStyle風格)
在 MyUserControl.OnPaint(PaintEventArgs的e)
這是類:
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
}
}
}
呃,等等,它*是*被絆倒。 –
它沒有被絆倒。獲取記錄的錯誤僅僅是DrawBorder調用失敗的錯誤。有一個單獨的日誌消息,說「從非UI線程調用OnPaint」。我們通過檢查應用程序主窗體上的InvokeRequired來確定。 –
然後GDI + barfs,因爲筆在同一時間在多個Graphics上下文中使用。這不應該讓你感到驚訝。 –