1: UsingSystem;
2: UsingSystem. Collections. Generic;
3: UsingSystem. LINQ;
4: UsingSystem. text;
5: UsingSystem. Threading;
6: UsingSystem. Threading. tasks;
7:
8: NamespaceSynchronizationsamples
9:{
10:Public ClassSharedstate
11:{
12:Private IntState = 0;
13:Private ObjectSyncroot =New Object();
14:Public IntState
15:{
16:Get {ReturnState ;}
17:Set {state =Value;}
18:}
19:
20:Public IntIncrementstate ()
21:{
22:ReturnInterlocked. increment (RefState );
23:
24:}
25:}
26:
27:Public ClassJob
28:{
29:Sharedstate;
30:PublicJob (sharedstate)
31:{
32:This. Sharedstate = sharedstate;
33:}
34:
35:Public VoidDothejob ()
36:{
37:For(IntI = 0; I <50000; I ++)
38:{
39:Sharedstate. incrementstate ();
40:}
41:}
42:}
43:ClassProgram
44:{
45:Static VoidMain (String[] ARGs)
46:{
47:IntNumtasks = 20;
48:VaR state =NewSharedstate ();
49:VaR tasks =NewTask [numtasks];
50:
51:For(IntI = 0; I <numtasks; I ++)
52:{
53:Tasks [I] =NewTask (NewJob (state). dothejob );
54:Tasks [I]. Start ();
55:}
56:
57:For(IntI = 0; I <numtasks; I ++)
58:{
59:Tasks [I]. Wait ();
60:}
61:Console. writeline ("Summarized {0 }", State. State );
62:Console. Read ();
63:}
64:}
65:}