-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReadOnlyThreeStepFlag.cs
61 lines (52 loc) · 1.77 KB
/
ReadOnlyThreeStepFlag.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
using System;
using System.Runtime.Serialization;
using System.Threading;
namespace HpTimeStamps
{
[DataContract]
internal struct ReadOnlyThreeStepFlag
{
public readonly ThreeStepFlagCode Code
{
get
{
int temp = _code;
return (ThreeStepFlagCode)temp;
}
}
public bool TryBegin()
{
const int wantToBe = (int)ThreeStepFlagCode.InProcess;
const int needToBeNow = (int)ThreeStepFlagCode.Clear;
return Interlocked.CompareExchange(ref _code, wantToBe, needToBeNow) == needToBeNow;
}
public bool TryErrorOut()
{
const int wantToBe = (int)ThreeStepFlagCode.Clear;
const int needToBeNow = (int)ThreeStepFlagCode.InProcess;
return Interlocked.CompareExchange(ref _code, wantToBe, needToBeNow) == needToBeNow;
}
public bool TryComplete()
{
const int wantToBe = (int)ThreeStepFlagCode.Complete;
const int needToBeNow = (int)ThreeStepFlagCode.InProcess;
return Interlocked.CompareExchange(ref _code, wantToBe, needToBeNow) == needToBeNow;
}
public void ErrorOutOrThrow()
{
if (!TryErrorOut()) throw new InvalidOperationException("Not in proper state to error out.");
}
public void CompleteOrThrow()
{
if (!TryComplete()) throw new InvalidOperationException("Not in proper state to complete.");
}
public override readonly string ToString() => "ReadOnlyThreeStepFlag: [" + Code + "].";
[NonSerialized] private volatile int _code;
}
internal enum ThreeStepFlagCode
{
Clear = 0,
InProcess = 1,
Complete = 2
}
}