-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathListing22.03.SynchronizingWithMonitor.cs
More file actions
76 lines (69 loc) · 1.75 KB
/
Listing22.03.SynchronizingWithMonitor.cs
File metadata and controls
76 lines (69 loc) · 1.75 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
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_03;
#region INCLUDE
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
#region HIGHLIGHT
#if NET9_0_OR_GREATER
static readonly Lock _Sync = new();
#else
static readonly object _Sync = new();
#endif
#endregion HIGHLIGHT
static int _Total = int.MaxValue;
static int _Count = 0;
public static int Main(string[] args)
{
if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); }
Console.WriteLine("Increment and decrementing " +
$"{_Total} times...");
// Use Task.Factory.StartNew for .NET 4.0
Task task = Task.Run(() => Decrement());
// Increment
for(int i = 0; i < _Total; i++)
{
#region HIGHLIGHT
bool lockTaken = false;
try
{
Monitor.Enter(_Sync, ref lockTaken);
_Count++;
}
finally
{
if(lockTaken)
{
Monitor.Exit(_Sync);
}
}
#endregion HIGHLIGHT
}
task.Wait();
Console.WriteLine($"Count = {_Count}");
return _Count;
}
public static void Decrement()
{
for(int i = 0; i < _Total; i++)
{
#region HIGHLIGHT
bool lockTaken = false;
try
{
Monitor.Enter(_Sync, ref lockTaken);
_Count--;
}
finally
{
if(lockTaken)
{
Monitor.Exit(_Sync);
}
}
#endregion HIGHLIGHT
}
}
}
#endregion INCLUDE