-
Notifications
You must be signed in to change notification settings - Fork 0
/
Defer.cs
93 lines (83 loc) · 2.75 KB
/
Defer.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Threading.Tasks;
namespace Recore
{
/// <summary>
/// Invokes an action when disposed.
/// </summary>
/// <remarks>
/// Not thread-safe.
/// Concurrent calls to dispose the object may result in the action being invoked
/// multiple times.
/// However, sequential calls to <see cref="Dispose"/> are idempotent.
/// If an instance of this type is created and never disposed, the callback will not be called.
/// By design, the callback is not called from the finalizer, which would happen non-determinstically.
/// </remarks>
public sealed class Defer : IDisposable
{
private readonly Action action;
private bool isDisposed = false;
/// <summary>
/// Initializes an object with an action to invoke when the object is disposed.
/// </summary>
public Defer(Action action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
this.action = action;
}
/// <summary>
/// Invokes the callback registered with the object and marks the object as disposed.
/// </summary>
public void Dispose()
{
if (isDisposed)
{
return;
}
action();
isDisposed = true;
}
}
/// <summary>
/// Invokes an asynchronous action when disposed.
/// </summary>
/// <remarks>
/// Not thread-safe.
/// Concurrent calls to dispose the object may result in the action being invoked
/// multiple times.
/// However, sequential calls to <see cref="DisposeAsync"/> are idempotent.
/// If an instance of this type is created and never disposed, the callback will not be called.
/// By design, the callback is not called from the finalizer, which would happen non-determinstically.
/// </remarks>
public sealed class AsyncDefer : IAsyncDisposable
{
private readonly AsyncAction action;
private bool isDisposed = false;
/// <summary>
/// Initializes an object with an action to invoke when the object is disposed.
/// </summary>
public AsyncDefer(AsyncAction action)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
this.action = action;
}
/// <summary>
/// Invokes the callback registered with the object and marks the object as disposed.
/// </summary>
public async ValueTask DisposeAsync()
{
if (isDisposed)
{
return;
}
await action();
isDisposed = true;
}
}
}