1

I have a class in my asp mvc app which keeps some "global" data. it is implemented as singleton. It looks something like this:

class InfoStrings  
{
    public List<string> strings = new List<string>();
    static InfoStrings me = null;

    private InfoStrings()
    { }
    public static InfoStrings GetMe()
    {
        if(me == null)
            me = new InfoStrings();

        return me;
    }
}

Now from controller's code I access this class by locking on it like this:

lock (InfoStrings.GetMe())
{
 ...
}

Ok, 2 questions:

1)Theoretically, can my InfoStrings object be garbage collected?

2)Am I doing proper locking there?

ren
  • 3,843
  • 9
  • 50
  • 95

3 Answers3

3

1)Theoretically, can my InfoStrings object be garbage collected?

No, it's a static field which once assigned won't be garbage collected.

2)Am I doing proper locking there?

I would recommend you locking on a private static object:

private static object _syncRoot = new object();
...
lock (_syncRoot)
{
    var instance = InfoStrings.GetMe();
}

You might also find the following article useful when implementing the singleton pattern in C#. Example:

public sealed class InfoStrings
{
    private InfoStrings()
    {
    }

    public static InfoStrings Instance 
    { 
        get { return Nested.instance; } 
    }

    private class Nested
    {
        static Nested()
        {
        }
        internal static readonly InfoStrings instance = new InfoStrings();
    }
}

and then you don't need to lock in order to obtain the instance:

var instance = InfoStrings.Instance;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

If you are working in .NET 4.0, then you don't have to do any of this. You can create a static readonly field of type Lazy, passing LazyThreadSafetyMode.ExecutionAndPublication to the constructor (along with your Func to indicate how to create the instance) to guarantee that the value will only be created once.

Then, you expose a property which simply calls the Lazy.Value property to return the lazy-loaded singleton value.

(Text copied from singleton pattern in vb)

Community
  • 1
  • 1
Lee Smith
  • 6,339
  • 6
  • 27
  • 34
0

You can find THE defacto singleton implementation here http://www.yoda.arachsys.com/csharp/singleton.html

BlackTigerX
  • 6,006
  • 7
  • 38
  • 48