Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Singleton thread safe

I have a singleton class similar to this

public class Singleton
{
    private static Singleton m_instance;
    private Timer m_timer;
    private static List<CustomObject> m_cacheObjects;

    private Singleton()
    {    
        m_cacheObjects = new List<CustomObject>();
        m_timer= new Timer(MyTimerCallBack, 
                           null, 
                           TimeSpan.FromSeconds(60), 
                           TimeSpan.FromSeconds(60));           
    }

    public static Singleton Instance
    {
        get
        {
            if (m_instance == null)
            {
                m_instance = new Singleton();
            }
            return m_instance;
        }
    }

    private void MyTimerCallBack(object state)
    {
        //******** Update the list by interval here ******************

        m_cacheObjects = UpdateTheList();
    }

    public void CallMe()
    {
        foreach (CustomObject obj in m_cacheObjects)
        {
            // do something here based on obj

            // The question is, does the m_cacheObjects is thread safe??
            // what happen if the m_cacheObjects is changed
            // during the loop interation?
        }
    }
}

The CallMe method will be called by web service:

  [WebMethod]
    public void CallMeWebService()
    {
        Singleton.Instance.CallMe();
    }

The questions: 1) Is the m_cacheObjects is thread safe? what happen if the m_cacheObjects is changed(because of the timer) during the loop interation (in the CallMe() )?

2) Is a new thread will be created when the Webservice CallMeWebService() is being called?

like image 952
user1553857 Avatar asked Jul 26 '12 08:07

user1553857


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

1: No, a static list is not automatically thread-safe; you must protect m_cacheObjects manually

2: That is an implementation detail; at first glance it looks like it exposes itself as a sync method, but how it does that is entirely up to it

Actually, your static initialization isn't thread-safe either; I could brute-force a scenario where two different Singleton instances were used. It would take repetition to produce it, but it would happen.

Frankly, unless you have a really good reason not to, the simplest but safest singleton pattern is simply:

private static readonly Singleton m_instance = new Singleton();
like image 182
Marc Gravell Avatar answered Oct 11 '22 04:10

Marc Gravell


//using System.Runtime.CompilerServices;

private static volatile Singelton _instance;

public static Singelton Instance
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get
    {
        if (_instance == null)
        {
            _instance = new Singelton();
        }
        return _instance;
    }
}

Explain:

[MethodImpl(MethodImplOptions.Synchronized)] This will tell the compiler that the access to "Instance" is "Synchronized" so the system take care about the calls to this Parameter.

This is Thread-Safe.

EDIT: (Also, the "Lock()" examples are not safe! Coz, u can disable the thread Safety with "Monitor.Exit(Singleton);")

like image 38
k1ll3r8e Avatar answered Oct 11 '22 04:10

k1ll3r8e