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