-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathListing22.05.AsyncMain.cs
More file actions
55 lines (48 loc) · 1.2 KB
/
Listing22.05.AsyncMain.cs
File metadata and controls
55 lines (48 loc) · 1.2 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
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_05;
#region INCLUDE
using System;
using System.Threading.Tasks;
public class Program
{
#if NET9_0_OR_GREATER
static readonly Lock _Sync = new();
#else
static readonly object _Sync = new();
#endif
static int _Total = int.MaxValue;
static int _Count = 0;
#region HIGHLIGHT
public static async Task<int> Main(string[] args)
#endregion HIGHLIGHT
{
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++)
{
lock(_Sync)
{
_Count++;
}
}
#region HIGHLIGHT
await task;
#endregion HIGHLIGHT
Console.WriteLine($"Count = {_Count}");
return _Count;
}
static void Decrement()
{
for(int i = 0; i < _Total; i++)
{
lock(_Sync)
{
_Count--;
}
}
}
}
#endregion INCLUDE