C # multithreading synchronization-use the monitor class

Source: Internet
Author: User
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:}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.