Search code examples
c#winformsobjectdisposedexception

"Cannot access a disposed object" when checking for IsDisposed and Disposing


When the application receives a call from the service, it opens a form for each call. The user must make his input in each window and the close it. In order to smooth the user's work I am trying to reactivate the window the user was working on when the next one is being shown.

The method for doing this is below:

private void ActivatePreviousActiveForm() {

    if (_activeWhenOpen != null && _activeWhenOpen.InvokeRequired) {
         if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)
              _activeWhenOpen.Invoke((MethodInvoker)ActivatePreviousActiveForm);
    } else
         if (_activeWhenOpen != null && !(_activeWhenOpen is FrmRuntimeError))
             _activeWhenOpen.Activate();
}

Sometime it throws ""Cannot access a disposed object" when reaching the line

if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)

Does anyone know why this would happen?


Solution

  • Try to invert the if condition:

    This line

    if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)

    has to become

    if (!_activeWhenOpen.IsDisposed || !_activeWhenOpen.Disposing)

    That is because the condition are checked in the order they are written, so your code may call Disposing on an object that is alredy disposed, raising your error.

    EDIT:

    I also think that you should change the || to a && , because if your window is not Disposed but is in Disposing status, you may have an error.