我有一個WinForms應用程序,其中包含帶有後臺工作程序的單個窗體。表單包含一個按鈕,通過RunWorkerAsync()啓動後臺工作器,另一個按鈕將退出應用程序。約1/3的時間,後臺工作人員已完成其工作後,應用程序會後,我退出按鈕點擊,像這樣的異常崩潰:.NET WinForms應用程序在出現未處理的System.NullReferenceException時崩潰
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=System.Drawing
StackTrace:
at System.Drawing.Graphics.Dispose(Boolean disposing)
at System.Drawing.Graphics.Finalize()
下面是該按鈕的事件處理程序退出應用程序:
private void buttonExit_Click(object sender, EventArgs e)
{
if (!buttonStartWorker.Enabled)
{
DialogResult dr = MessageBox.Show("Background worker is still running! Exit anyway?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dr == DialogResult.OK)
{
backgroundWorker.CancelAsync();
Close();
}
}
else
{
Close();
}
}
正如我剛纔所說,我不會退出應用程序,而後臺工作仍在運行,所以我們正在尋找這裏的代碼路徑只是關閉()調用。還有一個FormClosing事件處理程序,它調用close和處理我的USB相關句柄上的方法。該代碼如下:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// close and dispose all open handles to the USB device
if (hidHandle != null)
{
if (!(hidHandle.IsInvalid))
{
hidHandle.Close();
hidHandle.Dispose();
}
}
if (readHandle != null)
{
if (!(readHandle.IsInvalid))
{
readHandle.Close();
readHandle.Dispose();
}
}
if (writeHandle != null)
{
if (!(writeHandle.IsInvalid))
{
writeHandle.Close();
writeHandle.Dispose(); // unhandled exception seems to occur after this
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
有時writeHandle.Dispose之間()和應用程序實際上離開時,此異常正在發生。最讓我困惑的是事實是我的代碼從未明確地使用過System.Drawing,所以我無法跟蹤它。
對於它的價值,我的後臺工作執行以下操作:
- 它可以讀取和USB設備的一些數據寫入/
- 它創建了一個Web客戶端下載一些數據
- 它使幾個SOAP調用
有沒有人有什麼可以在System.Drawing中導致一個未處理的NullReferenceException的任何想法當應用程序(不顯式使用System.Dra翅膀)退出?
發佈完整的堆棧跟蹤請 – wal 2012-04-26 15:44:50