-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_ReducingTheOverheadWithLazyInitializations.cs
50 lines (45 loc) · 1.35 KB
/
_ReducingTheOverheadWithLazyInitializations.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
using Ch07.Domain;
using Common.Interfaces;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Ch07.Examples
{
public class _ReducingTheOverheadWithLazyInitializations : IBaseExecutor
{
public void Run()
{
SingleThreadEnsureInitialized();
//MultipleThreadEnsureInitialized();
}
static Data _data;
void SingleThreadEnsureInitialized()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Iteration {i}");
Initializer();
}
}
static bool _initialized;
static object _locker = new object();
void MultipleThreadEnsureInitialized()
{
Parallel.For(0, 10, (i) =>
{
//Console.WriteLine($"Iteration {i}");
Initializer();
});
}
private void Initializer()
{
Console.WriteLine($"Task with id {Task.CurrentId ?? 0}");
LazyInitializer.EnsureInitialized(ref _data, ref _initialized, ref _locker, () =>
{
Console.WriteLine($"Task with id {Task.CurrentId ?? 0} is Initializing data");
// Returns value that will be assigned in the ref parameter.
return new Data();
});
}
}
}