C#_ Keyword: The interpretation and use of lock

Source: Internet
Author: User

Defined

Lock keyword, a mutex, that sets the code inside the statement block ({}) to a critical section by locking an object.

If a thread encounters a mutex when executing code linearly, it must first request access to the mutex and, if successful, continues to linearly access the critical section code block after the mutex. The statement reads as follows:  

1 New Object (); 2 Lock (Thislock) 3 {4     // Critical Code section. 5 }

  The lock keyword ensures that when one thread is in the critical section of the code, the other thread does not enter the critical section. If another thread attempts to enter the locked code, it waits (that is, is blocked) until the object is freed.

Use
    • Locked objects

Locked objects cannot be of the public type, or lock ( this),Lock (typeof (MyType)), and lock ("MyLock") use are not compliant.

Lock objects do not affect external thread code only if they are not externally accessed. Becausethis,typeof (MyType) in lock (this), Lock (typeof (MyType)) and lock ("MyLock") is potentially externally accessible, external code with the same string as "MyLock" These objects are locked and have unpredictable effects on the process code. Therefore, it is recommended to use the private object as the lock object.

C#_ Keyword: The interpretation and use of 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.