Justin
Justin

Reputation: 85

When closing form I get An exception of type 'System.ObjectDisposedException' occurred in System.Windows.Forms.dll but was not handled in user code

Additional Information: Cannot access a disposed object. And it highlights this line of code:

 if (this.InvokeRequired)
        {
            this.Invoke(new TelemetryData(Telemetry_Data), new object[2] {data, updated});
            return;
        }

This happens when I try to exit my application and throws this exception. Not sure what code you guys need to help me figure this out but here is my onClosing code:

 private void FleetTrack_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (lblFTstatus.Text == "CONNECTED")
        {
            DialogResult dialog = MessageBox.Show("You are currently connected to FleetTrack™\n\nIf you exit now, you will lose all progress on this job.",
                "Exit FleetTrack™", MessageBoxButtons.YesNo);
            if (dialog == DialogResult.Yes)
            {
                dbConnect.Delete();
                Application.ExitThread();
            }
            else if (dialog == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
        else if (lblFTstatus.Text == "DISCONNECTED")
        {
            Application.ExitThread();

        }
    }

Upvotes: 3

Views: 11459

Answers (2)

user3337357
user3337357

Reputation:

private void Frm_FormClosing(object sender, FormClosingEventArgs e)
{
    Application.ExitThread();
}

Close thread using this.

Upvotes: 0

Zer0
Zer0

Reputation: 7354

You have a background thread attempting to marshal over to the GUI thread via Invoke. You close the form but the background thread continues running. The form is disposed of when Invoke is called so you get an ObjectDisposedException.

The dirty "fix" is to catch the exception. Since you're closing you may not care. But the real fix is to shut down your background threads before the form closes.

Upvotes: 3

Related Questions