Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if control was disposed

Tags:

c#

.net

winforms

In my application I have a user control that do async operations using thread pool. The thread pool method looks like:

private void AsyncFunction(object state)
    {
        ... do the calculation
        //refresh the grid data on the UI thread
        this.BeginInvoke(new MethodInvoker(() =>
                                               {
                          ... update the ui 
                                               }));
    }

My problem is that if the user closes the dialog ... the user control gets disposed and I get the exception:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Do you know a way to detect if the dialog was disposed? I don't want to hae a property on control that the dialog set when closed. Is there another way of solving this?

Thanks,

Radu

like image 868
Radu D Avatar asked Dec 16 '10 12:12

Radu D


2 Answers

Control.IsDisposed

like image 190
max Avatar answered Oct 20 '22 03:10

max


You can use Control.IsDisposed property.

try
{
    if(!this.IsDisposed) 
    {
        this.BeginInvoke(new MethodInvoker(() =>

                      {
                                // update my control
                      }
          ));
    }
}
catch ( InvalidOperationException )
{
    // Do something meaningful if you need to.
}
like image 36
Unmesh Kondolikar Avatar answered Oct 20 '22 03:10

Unmesh Kondolikar