-
-
Notifications
You must be signed in to change notification settings - Fork 424
/
Copy pathTState.cs
67 lines (59 loc) · 1.87 KB
/
TState.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace LanguageExt;
public class TState(
ConcurrentDictionary<object, IDisposable>? disps,
SynchronizationContext? syncContext,
CancellationToken token)
: IDisposable
{
public readonly CancellationToken Token = token;
public readonly SynchronizationContext? SynchronizationContext = syncContext;
public TState(SynchronizationContext? syncContext, CancellationToken token) : this(null, syncContext, token)
{
}
public Unit Using<A>(A value, Func<A, Unit> dispose)
{
object? key = value;
if (key is null) throw new InvalidCastException("can't cast the use value to object without it being null");
var disps1 = disps ?? new ConcurrentDictionary<object, IDisposable>();
disps1.TryAdd(key, new Cleaner<A>(value, dispose));
return default;
}
public Unit Using<A>(A value) where A : IDisposable =>
Using(value, x => { x.Dispose(); return default; });
public Unit Release<A>(A value)
{
object? key = value;
if (key is null) throw new InvalidCastException("can't cast the use value to object without it being null");
if (disps is not null && disps.TryRemove(key, out var disp))
{
disp.Dispose();
}
return default;
}
public void Dispose()
{
var disps1 = Interlocked.Exchange(ref disps, null);
if(disps1 is not null)
{
foreach (var d in disps1)
{
d.Value.Dispose();
}
}
}
record Cleaner<A>(A Value, Func<A, Unit> Free) : IDisposable
{
volatile int hasRun;
public void Dispose()
{
if (Interlocked.Exchange(ref hasRun, 1) == 0)
{
Free(Value);
}
}
}
}