@@ -33,17 +33,23 @@ public abstract class DisposableStateBase : IDisposalState
3333 // Since all write operations are done through Interlocked, no need for volatile.
3434 private int _disposeState = ALIVE ;
3535 protected int DisposalState => _disposeState ;
36+
37+ // Expected majority use will be 'alive'.
3638 public bool WasDisposed => _disposeState != ALIVE && _disposeState != DISPOSE_CALLED ;
3739
38- protected bool AssertIsAlive ( )
40+ /// <summary>
41+ /// Will throw if the object is disposed or has started disposal.
42+ /// </summary>
43+ /// <param name="strict">When true, will also throw if between alive and disposing states.</param>
44+ /// <returns>True if still alive.</returns>
45+ protected bool AssertIsAlive ( bool strict = false )
3946 {
40- if ( WasDisposed )
47+ if ( strict ? _disposeState != ALIVE : WasDisposed )
4148 throw new ObjectDisposedException ( GetType ( ) . ToString ( ) ) ;
4249
4350 return true ;
4451 }
4552
46-
4753 /* This is important because some classes might react to disposal
4854 * and still need access to the live class before it's disposed.
4955 * In addition, no events should exist during or after disposal. */
@@ -63,7 +69,7 @@ public event EventHandler BeforeDispose
6369 * Prevent adding events when already disposed.
6470 */
6571 AssertIsAlive ( ) ;
66- if ( _disposeState == DISPOSING )
72+ if ( _disposeState != ALIVE ) // Should not be adding events while event is firing...
6773 throw new InvalidOperationException ( "Adding an event listener while disposing is not supported." ) ;
6874
6975 /*
0 commit comments