-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBusyStack.cs
65 lines (54 loc) · 1.62 KB
/
BusyStack.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
using System;
using System.Diagnostics;
using System.Threading;
namespace MvvmScarletToolkit.Observables
{
/// <summary>
/// Will notify its owner via a provided action on if it contains more tokens
/// </summary>
public sealed class BusyStack : IBusyStack
{
private readonly Action<bool> _onChanged;
private int _items;
public BusyStack(in Action<bool> onChanged)
{
_onChanged = onChanged ?? throw new ArgumentNullException(nameof(onChanged));
}
public void Pull()
{
var oldValue = _items > 0;
Interlocked.Decrement(ref _items);
var newValue = _items > 0;
if (oldValue.Equals(newValue))
{
return;
}
InvokeOnChanged(newValue);
}
public void Push()
{
var oldValue = _items > 0;
Interlocked.Increment(ref _items);
var newValue = _items > 0;
if (oldValue.Equals(newValue))
{
return;
}
InvokeOnChanged(newValue);
}
/// <summary>
/// Returns a new <see cref="IDisposable"/> thats associated with <see cref="this"/> instance of a <see cref="IDisposable"/>
/// </summary>
/// <returns>a new <see cref="IDisposable"/></returns>
[DebuggerStepThrough]
public IDisposable GetToken()
{
return new BusyToken(this);
}
[DebuggerStepThrough]
private void InvokeOnChanged(bool newValue)
{
_onChanged(newValue);
}
}
}