Talking about the use of lock in c #

Source: Internet
Author: User

1. Start with the "simplest" Singleton mode:
 

Public class Singleton
{
Private static Singleton instance = null;
Private static readonly object syncRoot = new object ();

Private Singleton ()
{
}

Public static Singleton GetInstance ()
{
If (instance = null)
{
Lock (syncRoot)
{
If (instance = null)
{
Instance = new Singleton ();
}
}
}
Return instance;
}
}

People who have a better understanding of the basic knowledge of the design model should be familiar with the above Code. During the last interview, the examiner asked Lou pig to write a ticket. Although I have not deliberately used the design mode for programming for a long time, but for this Singleton mode, haha, although the Big husband is not angry with the color, however, at that time, the pig in the nc building was very eager to deliver the above answer. The interviewer gave me a few comments and asked, can the object instance in lock be directly replaced by instance? Whether a new object is redundant can be written in the following form:

Public class Singleton
{
Private static Singleton instance = null;
// Private static readonly object syncRoot = new object ();

Private Singleton ()
{
}

Public static Singleton GetInstance ()
{
If (instance = null)
{
Lock (instance) // can an instance replace syncRoot?
{
If (instance = null)
{
Instance = new Singleton ();
}
}
}
Return instance;
}
}

Even before this question, the interviewer asked a database design question and a few small questions about c # (I had a question that I was saying that it was "amazing", so I was afraid of it) I am very aware of the depth and cultivation of knowledge. Lou pig is already very cautious, but this problem still makes Lou pig feel confused again. No one has ever asked Lou pig this question before, Lou pig has never taken the initiative to think about it, his head is white, just want to calm down, the interviewer asked the same question again

Related Article

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.