Feedback

Singelton in C# – threadsicher implementiert

Sprache: C#

Das Singelton-Pattern ist wohl eins der einfachsten und praxisrelevantesten Designpatterns. Hier also einmal eine beispielhafte Implementierung in C#
public class Singelton
    {
        private static Singelton me = null;
        static readonly object padlock0 = new object(); //Zur Threadsicherheit

        private Singelton()
        {
            //Initialize
        }

        public static Singelton GetInstance()
        {
            lock (padlock0)
            {
                if(me == null) 
                {
                    me = new Singelton();
                }
                return me;
            }
        }
    }
public class Singelton
    {
        private static Singelton me = null;
        static readonly object padlock0 = new object(); //Zur Threadsicherheit

        private Singelton()
        {
            //Initialize
        }

        public static Singelton GetInstance()
        {
            lock (padlock0)
            {
                if(me == null) 
                {
                    me = new Singelton();
                }
                return me;
            }
        }
    }

2 Kommentare

  1. Warum so umständlich?
    [code]public static readonly Singleton Instance = new Singleton();[/code]

  2. Sorry, Michael, das ist Quatsch. Der Punkt ist ja, dass das Singleton threadsicher sein soll.

    OP:
    1. Das Teil heißt Singleton.
    2. Du hast folgendes vergessen zu erwähnen:
    2a. Diese Klasse darf [b]kein einziges[/b] public-Member haben.
    2b. [b]Jede public Methode[/b] – auch static, sofern sie auf die Instanz zugreifen – dieser Klasse muss am padlock0 synchronisiert werden, weil sonst die Aufrufe nicht atomar sind.