C # Lock statement and Application in singleton Mode

Source: Internet
Author: User

What is the lock statement in C?

The lock statement in C # regards the block in the lock as the critical section. When multiple threads access the code in the critical section, they must access the code in sequence. In a multi-threaded environment, it ensures that objects in the critical section are operated by only one thread to prevent objects from being changed multiple times.

Note: The lock object must be an unchangeable object; otherwise, another thread cannot be blocked from entering the critical section. Preferably Private Static readonly or private static. The common methods of lock (this), lock (typeof (mytype), and lock ("mylock") are unreasonable.

Cause:

1. lock (this), the main problem is that if the class is an instantiation class, this is only the current instance and cannot be locked, and even static classes can be locked, due to the size problem, it is more cost-effective to lock small objects.

2. the lock (typeof () problem lies in the locking of the static object part of the object type, locking all instances, slow; on the other hand, it is possible that other parts of the program are accessing this object and have been locked for you, which will cause the suspension of the lock statement. Original article (here's why: Since there's one type object for all instances of a class, it wowould appear that locking it wowould provide a lock equivalent to locking a static object contained in your class. you wocould lock all instances of the class, wait until other threads were done accessing any part of any instance, then lock access so you cocould access static members safely and without another thread interfering .)

3. the problem with lock ("") is that Microsoft treats strings with the same content as the same object. If you lock him here, it actually locks the same object, will block other places from locking strings.

 

A typical application of the lock statement is the singleton mode. One of the simplest ways to implement the singleton mode is to use static objects. As follows:

public class ABicycle {      private static ABicycle aBicycle = new ABicycle();       public ABicycle Instance()      {            return aBicycle;      }} 

 

This is the simplest way to implement the singleton mode, but one drawback is that if the abicycle class is called in advance, abicycle will be instantiated and there is no way to implement the instantiation delay. In this case, an association class can be used to avoid this problem. That is:

public class ABicycle {     public ABicycle Instance()     {            return ABicycleStance.Instance();     } } private class ABicycleStance {      internal static readonly ABicycle aBicycle = new ABicycle();      public ABicycle Instance()      {            return aBicycle;      } }

 

One idea of Singleton mode is to use the lock Statement of C. The simplest implementation method is:

if(... == null){ ... = new ... } return ...; 

 

If this is done, there is a problem that cannot be avoided, that is, it cannot be ensured that only one thread can instantiate the object, because it is possible that multiple threads can concurrently execute this, and the object is instantiated at the same time. Therefore, the lock statement must be referenced. The reference method is also exquisite. The most direct implementation method is:

Private Static readonly locker = new object (); // or write like this. // Private Static locker = new object (); lock (locker) {If (... = NULL ){...}}

 

The above practice is feasible, but there is a problem that the locker should be locked first each time a response is returned, which sacrifices some performance that does not have to be sacrificed. Therefore, you can modify it to the following practice:

private static readonly locker = new object();if(.. == null)   {       lock(locker)       {             if(... == null)            {      }       } } 

 

In this way, multithreading is safe, and you do not need to lock each time. You can only lock the object when it is determined that the object is not instantiated to avoid performance loss.

References:

Http://msdn.microsoft.com/zh-cn/library/c5kehkcz.aspx

Http://hi.baidu.com/benzhan/item/6304481419d6360dd1d66dff

Http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects

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.