Pure UX Logo Pure UX Title Cleansing Application Interfaces

Check Disposal Before Manipulating Windows Forms

Dev Tools & Code

It's a good idea to enclose the functionality of your forms' and user controls' exposed methods with a conditional to ensure the form isn't disposed or disposing.  Otherwise your code could potentially attempt to manipulate an object that is still around temporarily but in an uneditable state.

Here's an example.

Public Class MyForm
    Friend Sub DoSomething()
        If Not Me.IsDisposed AndAlso Not Me.Disposing Then
            Debug.WriteLine("Safe to manipulate the form.")
        End If
    End Sub
End Class

Comments

The primary situation in which this could cause an issue is if you are doing asynchronous work. In the callback, you should check for disposed UI components as the form might have disposed while the operation was in progress. For most synchronous UI thread code, this would not be a problem. I would only suggest doing the check in async callbacks or other such similar code.

Josh, I agree with what you're saying but with an exposed method you can't guarantee that whatever calls it isn't doing so asynchronously so I find it best to check it on the form rather than rely on everyone else to check the form before they call it.  In fact, if the method is being implemented through an interface the calling object may not even know that it's a form and therefore wouldn't know to check if it is disposed.  My example marked the method as friend but it could just as easily be public.

I wasn't specifically considering the situation with a publicly accessible method for off of a form, since I don't do that very often. In situations where you do that, I could see checking as you never know how it's being called.

Add comment




biuquote
Loading