CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: lock() question

  1. #1
    Join Date
    Sep 2008
    Location
    Netherlands
    Posts
    865

    lock() question

    I want to create a Singleton object. On MSDN and other places I found the same example like the one here:
    Code:
    public sealed class Singleton
    {
        static Singleton _instance = null;
        static readonly object _lock = new object();
    
        Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance==null)
                    {
                        _instance = new Singleton();
                    }
                    return _instance;
                }
            }
        }
    }
    It works, that's not the problem. But why is there a seperate object used for locking? Why not just use lock(_instance) instead of lock(_lock)?

  2. #2
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Re: lock() question

    Your question will be answered here.

    And creating a singleton can be made easier without using lock.

    Code:
    public sealed class Singleton
    {
        private static readonly Singleton _instance = new Singleton();
        
        private Singleton()
        {
        }
    
        public static Singleton Instance
        {
            get
            {
                return _instance;
            }
        }
    }
    Useful or not? Rate my posting. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured