-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathXmldocExample.cs
More file actions
35 lines (33 loc) · 1 KB
/
XmldocExample.cs
File metadata and controls
35 lines (33 loc) · 1 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
using System;
using System.Threading;
/// <summary>
/// A minimal threadsafe counter.
/// </summary>
class AtomicCounter
{
/// <summary>
/// The current value of the counter.
/// </summary>
int currentValue = 0;
/// <summary>
/// Increments the value of the counter.
/// </summary>
///
/// <param name="incrementBy">The amount to increment.</param>
/// <exception cref="System.OverflowException">If the counter would overflow.</exception>
/// <returns>The new value of the counter.</returns>
///
/// <remarks>This method is threadsafe.</remarks>
public int Increment(int incrementBy = 1)
{
int oldValue, newValue;
do
{
oldValue = currentValue;
newValue = oldValue + incrementBy;
if (newValue < 0) throw new OverflowException("Counter value is out of range");
}
while (oldValue != Interlocked.CompareExchange(ref currentValue, newValue, oldValue));
return newValue;
}
}