01.
public
sealed
class
MultiThreadSingleton<T> where T :
02.
{
03.
#region Private Fields
04.
/// <summary>
05.
///
06.
/// </summary>
07.
private
static
volatile T instance;
08.
09.
10.
/// sync lock for creating
11.
12.
object
synclock =
new
();
13.
14.
#endregion
15.
16.
#region Constructor
17.
18.
/// Initializes QMultiThreadSingleton
19.
20.
MultiThreadSingleton()
21.
22.
}
23.
24.
25.
26.
27.
28.
29.
T Instance
30.
31.
get
32.
33.
if
(instance ==
null
)
34.
35.
lock
(synclock)
36.
37.
38.
39.
var type =
typeof
(T);
40.
instance = Activator.CreateInstance(type,
true
as
T;
41.
42.
43.
44.
return
instance;
45.
46.
47.
48.
Program
void
Main(
string
[] args)
DemoClassOne test = MultiThreadSingleton<DemoClassOne>.Instance;
test.SampleInetgerProperty = 99;
test.DemoPropertyOne =
"No Operation"
;
Parallel.For(0, 5, i => {
ThreadTest threadObject =
ThreadTest(i);
DemoClassOne singletonObj = MultiThreadSingleton<DemoClassOne>.Instance;
threadObject.MyProperty = singletonObj;
Parallel.For(0, 2, j => {
(j == 0)
(threadObject)
threadObject.OperationOne();
else
threadObject.OperationTwo();
});
var newobject = MultiThreadSingleton<DemoClassOne>.Instance;
Console.WriteLine(
"Thread {0} ,Final , MyProperty.CheckBoolProoperty {1} , MyProperty.SampleInetgerProperty {2} ,MyProperty.DemoPropertyOne {3}"
,
System.Threading.Thread.CurrentThread.ManagedThreadId, newobject.CheckBoolProoperty, newobject.SampleInetgerProperty, newobject.DemoPropertyOne);
Console.ReadLine();
ThreadTest
DemoClassOne MyProperty {
set
; }
int
ThreadId {
49.
50.
randomNumber = 0;
51.
52.
ThreadTest(
threadId)
53.
54.
this
.ThreadId = threadId;
55.
.randomNumber =
Random().Next(2, 12);
56.
57.
58.
59.
OperationOne()
60.
61.
"Thread {0} ,OperationOne Start , MyProperty.CheckBoolProoperty {1} , MyProperty.SampleInetgerProperty {2} ,MyProperty.DemoPropertyOne {3}"
62.
.ThreadId,
.MyProperty.CheckBoolProoperty,
.MyProperty.SampleInetgerProperty,
.MyProperty.DemoPropertyOne);
63.
(!
.MyProperty.CheckBoolProoperty)
64.
65.
.MyProperty.DemoPropertyOne =
"Operation 1"
66.
.MyProperty.SampleInetgerProperty =
.ThreadId * 3;
67.
.MyProperty.CheckBoolProoperty = !
.MyProperty.CheckBoolProoperty;
68.
69.
70.
"Thread {0} ,OperationOne End , MyProperty.CheckBoolProoperty {1} , MyProperty.SampleInetgerProperty {2} ,MyProperty.DemoPropertyOne {3}"
71.
72.
73.
74.
75.
76.
OperationTwo()
77.
78.
"Thread {0} ,OperationTwo Start , MyProperty.CheckBoolProoperty {1} , MyProperty.SampleInetgerProperty {2} ,MyProperty.DemoPropertyOne {3}"
79.
80.
(
81.
82.
"Operation 2"
83.
84.
85.
86.
87.
"Thread {0} ,OperationTwo End , MyProperty.CheckBoolProoperty {1} , MyProperty.SampleInetgerProperty {2} ,MyProperty.DemoPropertyOne {3}"
88.
89.
90.
91.
92.
93.
Naomi N edited Revision 1. Comment: Article needs more work
Can you explain what this code is doing, and when/why you would want to do it? Is this for the August C# Guru contest? If so, is it added to that page yet?
Thanks!