title: Why C# singleton class sometimes calls two method in multi threading?
body: <p>I am having issue with my singleton class in multi threading environment. This sample program calls method A &amp; B on separate threads. Normally this works ok. </p>
  
  <p>In some cases as shown in the last result at bottom </p>
  
  <ul>
  <li>method A call starts</li>
  <li>method B call starts</li>
  <li>method B call ends</li>
  <li>then method A call ends&lt;---- why is this happening out of order ?</li>
  </ul>
  
  <p>Is this because I am not performing double lock ? 
  How do I ensure that this does not happen ?</p>
  
  <p>Caller</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
              ThreadPool.QueueUserWorkItem(new WaitCallback(CallonThread));
              Singleton.Instance.Test("B");
              Console.ReadKey();
  
      }
  
      static void CallonThread(object a)
      {
          Singleton.Instance.Test("A");
      }
  }
  </code></pre>
  
  <p>Singleton Class</p>
  
  <pre><code>public class Singleton
  {
      static readonly object Padlock = new object();
      private static Singleton _instance;
      protected Singleton()
      {
      }
      public static Singleton Instance
      {
          get
          {
              lock (Padlock)
              {
                  if (_instance == null)
                  {
                      _instance = new Singleton();
                  }
                  return _instance;
              }
          }
      }
      public void Test(string id)
      {
          if (id == "A")
          {
              new Data().MethodA();
          }
          else
          {
              new Data().MethodB();
          }
      }
  }
  </code></pre>
  
  <p>Data class</p>
  
  <pre><code>public class Data
  {
      public void MethodA()
      {
          Console.WriteLine("Start Method A");
          Console.WriteLine("End Method A");
      }
      public void MethodB()
      {
          Console.WriteLine("Start Method B");
          Console.WriteLine("End Method B");
      }
  }
  </code></pre>
  
  <p>Result
  <a href="https://i.stack.imgur.com/mlrft.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mlrft.png" alt="enter image description here"></a></p>