tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
ReferenceCountingContainer.cs
Go to the documentation of this file.
1using System;
2using System.Threading.Tasks;
3
5{
11 sealed class ReferenceCountingContainer<TWrapped, TReference>
12 where TWrapped : class
13 where TReference : ReferenceCounter<TWrapped>, new()
14 {
18 public TWrapped Instance { get; }
19
23 public Task OnZeroReferences
24 {
25 get
26 {
28 {
29 if (referenceCount == 0)
30 return Task.CompletedTask;
31 return onZeroReferencesTcs!.Task;
32 }
33 }
34 }
35
39 readonly object referenceCountLock;
40
44 TaskCompletionSource? onZeroReferencesTcs;
45
50
55 public ReferenceCountingContainer(TWrapped instance)
56 {
57 Instance = instance ?? throw new ArgumentNullException(nameof(instance));
58
59 referenceCountLock = new object();
60 }
61
66 public TReference AddReference()
67 {
69 {
70 if (referenceCount++ == 0)
71 onZeroReferencesTcs = new TaskCompletionSource();
72
73 try
74 {
75 var reference = new TReference();
76 reference.Initialize(Instance, () =>
77 {
79 if (--referenceCount == 0)
80 onZeroReferencesTcs!.SetResult();
81 });
82 return reference;
83 }
84 catch
85 {
87 throw;
88 }
89 }
90 }
91 }
92}
Class used for counting references with ReferenceCountingContainer<TWrapped, TReference>.
TaskCompletionSource? onZeroReferencesTcs
Backing TaskCompletionSource for OnZeroReferences.
TReference AddReference()
Create a new TReference to the Instance.
ReferenceCountingContainer(TWrapped instance)
Initializes a new instance of the ReferenceCountingContainer<TWrapped, TReference> class.
Task OnZeroReferences
A Task that completes when there are no TReference s active for the Instance.
readonly object referenceCountLock
lock object for referenceCount.