How can I tell if a C # control has been unloaded?

In my C # Windows Forms application, I have a custom control that contains other controls and executes its own logic. One is a pending call (triggered by a timer) that performs certain actions after the user has finished typing (real-time text). It refers to other controls for this, one of which is the text input control. This method is called 500ms after the last input event.

Now I have a problem where a pending call is made during the application termination. When I enter some text, wait for about 500ms (it works every time) and then press Alt + F4 to close the window, the application throws a NullReferenceException when trying to access the text input control. This does not happen when I close the window immediately after the last input or a second or more after.

It seems that the control is located or something and its methods can no longer access the controls. Thus, when a control is placed in this state (by whoever or whatever is this state), this timer must first be stopped so that the controls can be safely positioned.

I've already tried to stop the timer in the OnHandleDestroyed (overridden) method and at the beginning of the constructor-generated Dispose method. Nothing helped.

This procedure works fine in normal forms when stopping timers in the overridden OnFormClosed method before calling base.OnFormClosed (). I just cannot find a suitable event in the custom control.

+2


source to share


1 answer


Try this in your UserControl:

bool isDisposed;
protected override void Dispose(bool disposeManaged)
{
    if(!isDisposed)
    {
        if(disposeManaged)
        {
            //Dispose your timer here
        }
        isDisposed = true;
    }
}

      



Another possibility is that one of your UI classes is not doing its cleanup. For example. it registers for an event, but does not unregister when manually located. It is never collected by the GC and when the event is fired next time it tries to access some members that were set to null at the time of the call Dispose(...)

earlier.

Another possibility is that you have a more complex race condition in your code, but it's hard to tell from here.

+1


source







All Articles