C # Lock keyword,

Source: Internet
Author: User

C # Lock keyword,

The lock keyword marks the statement block as a critical section to obtain the mutex lock of a given object, execute the statement, and then release the lock.

 

The lock statement uses Monitor. enter and Monitor. exit, that is, execute Monitor when lock (this. enter (this). Execute Monitor at the end of braces. exit (this ). what does it mean? For any object, the first part of the memory places the addresses of all methods, and the second part places an index, it points to a SyncBlock in the SyncBlock Cache area of the CLR. what does it mean? That is to say, when you execute Monitor. Enter (Object), if the index value of the object is negative, select a SyncBlock from the SyncBlock Cache and put its address in the index of the object. In this way, the object-marked locking is completed. If other threads want to perform the Monitor. Enter (object) operation again, they will get the index with a positive number of objects, and then wait. Until the index changes to negative, that is, the thread uses Monitor. Exit (object) to change the index to negative.


Note the following when using lock:

1. lock cannot lock Null values. An object can point to Null, but Null does not need to be released. (Refer to: Understand all null)
2. lock cannot lock the string type, although it is also of the reference type. The string type is "Reserved" by CLR"

This means that there is only one instance for any given string in the entire program, and the same object represents the text in all threads in all running application domains. Therefore, as long as a lock is placed on a string with the same content anywhere in the application process, all instances of the string in the application will be locked. Therefore, it is best to lock private or protected members that are not temporarily retained.
3. The lock object is the memory boundary of a program block.
4. The value type cannot be locked, because the object in the red text is released, and the value type is not of the reference type.

5. lock to avoid locking public objects or objects not controlled by the program.
For example, if the instance can be publicly accessed, lock (this) may be faulty because uncontrolled Code may also lock the object. This may cause a deadlock, that is, two or more threads are waiting to release the same object. For the same reason, locking public data types (compared to objects) may also cause problems.
When lock (this) is used, the value of the member variable of the class may be changed by a method not in the critical section.

 

Application Scenario: It is often used to prevent uncertain exceptions in public variable values caused by multi-thread operations, so as to ensure operation security.

 

Example

// statements_lock2.csusing System;using System.Threading;class Account{    private Object thisLock = new Object();    int balance;    Random r = new Random();    public Account(int initial)    {        balance = initial;    }    int Withdraw(int amount)    {        // This condition will never be true unless the lock statement        // is commented out:        if (balance < 0)        {            throw new Exception("Negative Balance");        }        // Comment out the next line to see the effect of leaving out         // the lock keyword:        lock(thisLock)        {            if (balance >= amount)            {                Console.WriteLine("Balance before Withdrawal :  " + balance);                Console.WriteLine("Amount to Withdraw        : -" + amount);                balance = balance - amount;                Console.WriteLine("Balance after Withdrawal  :  " + balance);                return amount;            }            else            {                return 0; // transaction rejected            }        }    }    public void DoTransactions()    {        for (int i = 0; i < 100; i++)        {            Withdraw(r.Next(1, 100));        }    }}class Test{    static void Main()    {        Thread[] threads = new Thread[10];        Account acc = new Account(1000);        for (int i = 0; i < 10; i++)        {            Thread t = new Thread(new ThreadStart(acc.DoTransactions));            threads[i] = t;        }        for (int i = 0; i < 10; i++)        {            threads[i].Start();        }    }}

Provided by "figure douluo"

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.