-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeCounter.cs
41 lines (35 loc) · 1.35 KB
/
SafeCounter.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
namespace Searcher;
/// <summary>
/// This is a thread safe Int32 counter using Interlocked.Increment etc
/// </summary>
/// <remarks>
/// Create a new counter with an optional start value
/// </remarks>
internal sealed class SafeCounter(int counter = 0) // this class exists to wrap this field and prevent direct access
{
/// <summary>
/// Get the current value of the counter
/// </summary>
public int Value => counter; // no need for Interlocked here, Int32 is atomic on both 32 and 64 bit
/// <summary>
/// Increment the counter in a thread safe way. Lock free
/// </summary>
/// <returns>The incremented value</returns>
public int Increment() => Interlocked.Increment(ref counter);
/// <summary>
/// Decrement the counter in a thread safe way. Lock free
/// </summary>
/// <returns>The decremented value</returns>
public int Decrement() => Interlocked.Decrement(ref counter);
/// <summary>
/// Reset the counter in a thread safe way. Lock free
/// </summary>
/// <returns>The original value</returns>
public int Reset(int newvalue = 0) => Interlocked.Exchange(ref counter, newvalue);
/// <summary>
/// Add a value to the counter in a thread safe way. Lock free
/// </summary>
/// <returns>The new value</returns>
public int Add(int value) => Interlocked.Add(ref counter, value);
public override string ToString() => counter.ToString();
}