tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
ReferenceCounter.cs
Go to the documentation of this file.
1using System;
2
4{
9 abstract class ReferenceCounter<TInstance> : IDisposable
10 where TInstance : class
11 {
15 protected TInstance Instance => actualInstance ?? throw UninitializedOrDisposedException();
16
20 readonly object initDisposeLock;
21
25 TInstance? actualInstance;
26
31
36
40 protected ReferenceCounter()
41 {
42 initDisposeLock = new object();
43 }
44
46 public void Dispose()
47 {
48 lock (initDisposeLock)
49 {
50 referenceCleanupAction?.Invoke();
52 actualInstance = null;
53 }
54 }
55
61 public void Initialize(TInstance instance, Action referenceCleanupAction)
62 {
63 ArgumentNullException.ThrowIfNull(instance);
64
65 ArgumentNullException.ThrowIfNull(referenceCleanupAction);
66
67 lock (initDisposeLock)
68 {
69 if (initialized)
70 throw new InvalidOperationException($"{nameof(ReferenceCounter<TInstance>)} already initialized!");
71
72 actualInstance = instance;
73 this.referenceCleanupAction = referenceCleanupAction;
74 initialized = true;
75 }
76 }
77
82 protected void DangerousDropReference()
83 {
85 }
86
91 InvalidOperationException UninitializedOrDisposedException()
92 {
93 if (initialized)
94 return new ObjectDisposedException(nameof(ReferenceCounter<TInstance>));
95
96 return new InvalidOperationException($"{nameof(ReferenceCounter<TInstance>)} not initialized!");
97 }
98 }
99}
Class used for counting references with ReferenceCountingContainer<TWrapped, TReference>.
void DangerousDropReference()
Prevents the aquired reference from being dropped when Dispose is called.
readonly object initDisposeLock
The lock object for Initialize(TInstance, Action) and Dispose.
void Initialize(TInstance instance, Action referenceCleanupAction)
Initialize the ReferenceCounter<TInstance>.
TInstance Instance
The referenced TInstance .
bool initialized
If the ReferenceCounter<TInstance> was initialized.
ReferenceCounter()
Initializes a new instance of the ReferenceCounter<TInstance> class.
InvalidOperationException UninitializedOrDisposedException()
Throw the appropriate InvalidOperationException when the ReferenceCounter<TInstance> is uninitialized...
Action? referenceCleanupAction
The Action to take when Dispose is called.
TInstance? actualInstance
Backing field for Instance.