-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathScope.cs
More file actions
96 lines (75 loc) · 2.54 KB
/
Scope.cs
File metadata and controls
96 lines (75 loc) · 2.54 KB
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
94
95
96
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
namespace Microsoft.ClearScript.Util
{
internal interface IScope<out TValue>: IDisposable
{
TValue Value { get; }
}
internal static class Scope
{
public static IDisposable Create(Action enterAction, Action exitAction)
{
enterAction?.Invoke();
return new ScopeImpl(exitAction);
}
public static IDisposable Create<TArg>(Action<TArg> enterAction, Action exitAction, in TArg arg)
{
enterAction?.Invoke(arg);
return new ScopeImpl(exitAction);
}
public static IScope<TValue> Create<TValue>(Func<TValue> enterFunc, Action<TValue> exitAction)
{
var value = (enterFunc is not null) ? enterFunc() : default;
return new ScopeImpl<TValue>(value, exitAction);
}
public static IScope<TValue> Create<TArg, TValue>(Func<TArg, TValue> enterFunc, Action<TValue> exitAction, in TArg arg)
{
var value = (enterFunc is not null) ? enterFunc(arg) : default;
return new ScopeImpl<TValue>(value, exitAction);
}
#region Nested type: ScopeImpl
private sealed class ScopeImpl : IDisposable
{
private readonly Action exitAction;
private readonly OneWayFlag disposedFlag = new();
public ScopeImpl(Action exitAction)
{
this.exitAction = exitAction;
}
#region IDisposable implementation
public void Dispose()
{
if (disposedFlag.Set())
{
exitAction?.Invoke();
}
}
#endregion
}
#endregion
#region Nested type: ScopeImpl<TValue>
private sealed class ScopeImpl<TValue> : IScope<TValue>
{
private readonly Action<TValue> exitAction;
private readonly OneWayFlag disposedFlag = new();
public ScopeImpl(TValue value, Action<TValue> exitAction)
{
this.exitAction = exitAction;
Value = value;
}
#region IScope<TValue> implementation
public TValue Value { get; }
public void Dispose()
{
if (disposedFlag.Set())
{
exitAction?.Invoke(Value);
}
}
#endregion
}
#endregion
}
}