-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDefer.linq
More file actions
38 lines (27 loc) · 792 Bytes
/
Defer.linq
File metadata and controls
38 lines (27 loc) · 792 Bytes
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
<Query Kind="Program">
<Namespace>System.Buffers</Namespace>
</Query>
void Main()
{
var buffer = ArrayPool<byte>.Shared.Rent(1);
using var _ = Defer(b =>
{
"I got invoked after".Dump();
ArrayPool<byte>.Shared.Return(b);
}, buffer);
"I got invoked prior to mod of buffer".Dump();
buffer.Dump();
buffer[0] = 3;
"I got the buffer modified".Dump();
buffer.Dump();
}
static DeferDisposable<T> Defer<T>(Action<T> action, T param1) =>
new DeferDisposable<T>(action, param1);
// struct to avoid allocation
internal readonly struct DeferDisposable<T1> : IDisposable
{
readonly Action<T1> _action;
readonly T1 _param1;
public DeferDisposable(Action<T1> action, T1 param1) => (_action, _param1) = (action, param1);
public void Dispose() => _action.Invoke(_param1);
}