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:BoolLocktaken =False;
23:Monitor. tryenter (syncroot, 500,RefLocktaken );
24:If(Locktaken)
25:{
26:Try
27:{
28:Return++ State;
29:}
30:Finally
31:{
32:Monitor. Exit (syncroot );
33:}
34:}
35:Else
36:{
37:ReturnState;
38:}
39:}
40:}
41:
42:Public ClassJob
43:{
44:Sharedstate;
45:PublicJob (sharedstate)
46:{
47:This. Sharedstate = sharedstate;
48:}
49:
50:Public VoidDothejob ()
51:{
52:For(IntI = 0; I <50000; I ++)
53:{
54:Sharedstate. incrementstate ();
55:}
56:}
57:}
58:ClassProgram
59:{
60:Static VoidMain (String[] ARGs)
61:{
62:IntNumtasks = 20;
63:VaR state =NewSharedstate ();
64:VaR tasks =NewTask [numtasks];
65:
66:For(IntI = 0; I <numtasks; I ++)
67:{
68:Tasks [I] =NewTask (NewJob (state). dothejob );
69:Tasks [I]. Start ();
70:}
71:
72:For(IntI = 0; I <numtasks; I ++)
73:{
74:Tasks [I]. Wait ();
75:}
76:Console. writeline ("Summarized {0 }", State. State );
77:Console. Read ();
78:}
79:}
80:}