C # 's Lock

Source: Internet
Author: User

The lock keyword marks a statement block as a critical section by obtaining a mutex for a given object, executing the statement, and then releasing the lock.

classProgram {Static voidMain (string[] args) {Thread T=NewThread (lockobject.monitorincrement); Thread T1=NewThread (NewThreadStart (lockobject.lockincrement));                       T.start (); T1.                  Start (); }    }     Public classLockObject {/// <summary>        ///multi-threaded shared data/// </summary>         Private Static intCounter =0; /// <summary>        ///synchronizing objects, recommending this notation///you should avoid locking the public type, or the instance will go beyond the control of your code///details such as: Lock (This), Lock (typeof (MyType)) and lock ("MyLock")/// </summary>         Private ReadOnly Static ObjectSynisynchronize =New Object();  Public Static voidmonitorincrement () {///Monitor.Enter and Monitor.Exit are equivalent to lockMonitor.Enter (synisynchronize); Thread.Sleep ( +); Counter++; Console.WriteLine ("monitorincrement counter={0}", counter);        Monitor.Exit (synisynchronize); }         Public Static voidlockincrement () {///Lock calls Monitor.Enter at the beginning///call Monitor.Exit at the end.             Lock(synisynchronize) {counter++; Console.WriteLine ("lockincrement counter={0}", counter); }        }    }

The results of the operation are as follows:

C # 's Lock

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.