Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8527733
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:38:21+00:00 2026-06-11T08:38:21+00:00

We get an ObjectDisposedException from a call to Invoke on a Form that hasn’t

  • 0

We get an ObjectDisposedException from a call to Invoke on a Form that hasn’t yet been disposed. Here’s some sample code demonstrating the problem:

public partial class Form2 : Form
{
    void Form2_Load(object sender, EventArgs e)
    {
        // Start a task that does an Invoke on this control
        Task.Factory.StartNew(TaskWork); 

        // Sleep here long enough to allow the task that does the Invoke 
        // to execute to the point where it has:
        // a. Posted the message and 
        // b. is waiting 
        Thread.Sleep(500);

        // Cause ShowDialog to return by setting the DialogResult
        DialogResult = DialogResult.OK;
    }

    void TaskWork()
    {
        // This call doesn't return, but instead throws an ObjectDisposedException
        this.Invoke((MethodInvoker)(() => MessageBox.Show("Invoke succeeded")));
    }
}

Here’s the calling code from Form1 (the main form) which I never close:

public partial class Form1 : Form
{
    Form2 m_form2 = new Form2();

    void Form1_Load(object sender, EventArgs e)
    {
        // Call ShowDialog, but don't dispose it.
        m_form2.ShowDialog();

        // Cause the finalizers to run.  This causes an AggregateException to be thrown
        // due to the unhandled ObjectDisposedException from the Task.
        GC.Collect(); 
    }
}

We dug in to the Microsoft source, and found the exception is created during the call to DestroyHandle (below). DestroyHandle is being called by ShowDialog as it is finishing.

From source.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\fx\src\WinForms\Managed\System\WinForms\Control.cs\1305376\Control.cs:

protected virtual void DestroyHandle() {
    // ...
        // If we're not recreating the handle, then any items in the thread callback list will
        // be orphaned.  An orphaned item is bad, because it will cause the thread to never 
        // wake up.  So, we put exceptions into all these items and wake up all threads. 
        // If we are recreating the handle, then we're fine because recreation will re-post
        // the thread callback message to the new handle for us. 
        //
        if (!RecreatingHandle) {
            if (threadCallbackList != null) {
                lock (threadCallbackList) { 
                    Exception ex = new System.ObjectDisposedException(GetType().Name);

                    while (threadCallbackList.Count > 0) { 
                        ThreadMethodEntry entry = (ThreadMethodEntry)threadCallbackList.Dequeue();
                        entry.exception = ex; 
                        entry.Complete();
                    }
                }
            } 
        }
    // ...
}    

Questions:

  1. Why is ShowDialog destroying the handle (when I might re-use this form)?

  2. Why am I getting an ObjectDisposedException–its very misleading (since its not disposed). Its as if the code expected the handle would be destroyed only when the object was disposed (which is what I was expecting).

  3. Should this be valid? That is, should I be allowed to Invoke on to a control after ShowDialog?

Notes:

  1. Doing a second .ShowDialog() causes a new handle to be created.

  2. If after doing .ShowDialog() I try to do an Invoke, I get an InvalidOperationException stating that “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.”

  3. If after doing .ShowDialog() I access the Handle property, and then do an Invoke, it will succeed.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T08:38:22+00:00Added an answer on June 11, 2026 at 8:38 am

    Why is ShowDialog destroying the handle (when I might re-use this form)?

    To destroy the native window and make it disappear. The Handle property will be IntPtr.Zero after this.

    Why am I getting an ObjectDisposedException–its very misleading (since its not disposed).

    Yes, it is misleading in case of a dialog. The code was written to deal with the more common case of a form that’s displayed with Show(). Once the native window is destroyed, it works down the queue of pending invokes and marks them complete. And sets their “last exception raised” status to ObjectDisposedException (entry.exception in your Reference Source snippet). It does this explicitly to prevent any invoked code from running with the native window gone, such code will very commonly die with an ODE. It just jumps the gun and raises the exception early. You could argue that an InvalidOperationException would be more appropriate, but they chose ODE.

    Should this be valid? That is, should I be allowed to Invoke on to a control after ShowDialog?

    No, that cannot work. The value of the Handle property is required to figure out what thread to invoke to. But it is IntPtr.Zero after ShowDialog() returns.

    You hit a corner case here, but the general strategy must always be that you ensure that threads are completed or terminated before you allow the form to close. More about that in this answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that sporadically throws this exception: System.ObjectDisposedException: Cannot access a disposed
I use NHiberante at my win service. Sometimes I get System.ObjectDisposedException: Session is closed!
Get class from div inside an li and add to the same li. The
GET is a convenient method to post the form id, post the website id
I am receiving data from a device that's sending information over the serial port
Strange one that I don't still get, is this: Say, try { stateClient.Socket.BeginSend(messagePrefixed, 0,
I have a form that spawns a BackgroundWorker, that should update form's own textbox
I have a class that I created and in the class I do some
Get sunrise time and sun set times from xml from web. This is the
Get data week-wise my mysql since jan-2011. Timestamp is unix time stamp.so that i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.