I have a WinForms app that contains a single form with a background worker. The form contains a button that starts the background worker via RunWorkerAsync() and another button that will exit the application. About 1/3 of the time, after the background worker has completed its work, the application will crash after I click on the Exit button with an exception like this:
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()
Here is the event handler for the button that exits the application:
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();
}
}
As I said earlier, I'm not exiting the application while the background worker is still running so the code path we're looking at here is just the Close() call. There's also a FormClosing event handler which calls close and dispose methods on my USB-related handles. That code is as follows:
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());
}
}
Sometime between writeHandle.Dispose() and the time the application actually exits, this exception is occurring. The thing that's confusing me the most is the fact that my code never explicitly makes use of System.Drawing so I'm having trouble tracking this down.
For what it's worth, my background worker does the following:
- It reads and writes some data to/from a USB device
- It creates a web client to download some data
- It makes a few SOAP calls
Does anyone have any ideas on what could be causing an unhandled NullReferenceException in System.Drawing when an application (that doesn't explicitly use System.Drawing) exits?