-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
113 lines (93 loc) · 2.7 KB
/
Program.cs
File metadata and controls
113 lines (93 loc) · 2.7 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SingletonPattern3
{
public class PeriodParser
{
private static PeriodParser instance = new PeriodParser();
private PeriodParser()
{
}
public static PeriodParser GetInstance()
{
return instance;
}
}
public sealed class COMManager
{
private static COMManager instance;
public string Value { get; private set; }
private readonly static object _lock = new object();
private COMManager(string value)
{
this.Value = value;
}
public static COMManager GetInstance(string value)
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
instance = new COMManager(value);
}
}
return instance;
}
}
// Потокобезопасная реализация без использования lock
public class Singleton2
{
private static readonly Singleton2 instance = new Singleton2();
public string Date { get; private set; }
private Singleton2()
{
Date = System.DateTime.Now.TimeOfDay.ToString();
}
public static Singleton2 GetInstance()
{
return instance;
}
}
// Nested class
public class Singleton
{
public string Date { get; private set; }
public static string text = "hello";
private Singleton()
{
Console.WriteLine($"Singleton ctor {DateTime.Now.TimeOfDay}");
Date = DateTime.Now.TimeOfDay.ToString();
}
public static Singleton GetInstance()
{
Console.WriteLine($"GetInstance {DateTime.Now.TimeOfDay}");
Thread.Sleep(500);
return Nested.instance;
}
private class Nested
{
static Nested() { }
internal static readonly Singleton instance = new Singleton();
}
}
class Program
{
static void Main(string[] args)
{
var t1 = Task.Run(() =>
{
Thread.Sleep(300);
COMManager manager = COMManager.GetInstance("Foo");
Console.WriteLine(manager.Value);
});
var t2 = Task.Run(() =>
{
COMManager manager = COMManager.GetInstance("Barr");
Console.WriteLine(manager.Value);
});
Task.WaitAll(t1, t2);
}
}
}