Skip to content

Commit ad15fed

Browse files
author
Oren (electricessence)
committed
Improved disposal assertions.
1 parent ef9d76b commit ad15fed

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

DisposableStateBase.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -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
/*

Open.Disposable.csproj

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@
1717
<PackageProjectUrl>https://github.com/electricessence/Open.Disposable/</PackageProjectUrl>
1818
<RepositoryUrl>https://github.com/electricessence/Open.Disposable/</RepositoryUrl>
1919
<RepositoryType>git</RepositoryType>
20-
<Version>2.2.1</Version>
20+
<Version>2.3.0</Version>
2121
<PackageReleaseNotes></PackageReleaseNotes>
22-
<AssemblyVersion>2.2.1.0</AssemblyVersion>
23-
<FileVersion>2.2.1.0</FileVersion>
22+
<AssemblyVersion>2.3.0.0</AssemblyVersion>
23+
<FileVersion>2.3.0.0</FileVersion>
2424
<PackageLicenseExpression>MIT</PackageLicenseExpression>
2525
</PropertyGroup>
2626

0 commit comments

Comments
 (0)