Singleton Pattern

Singleton pattern is a simple design pattern in software practice and sometimes considered as an anti-pattern due its tight coupling nature.

A very simple non thread safe implementation of the Singleton pattern would be like this.

Singleton non thread safe

class Singleton
{
  privatestatic Singleton _instance;
  private Singleton()
  {
    Console.WriteLine(Singleton instantiated);
  }
 
publicstatic Singleton SingletonInstance
{
  get
   {
        if (_instance ==null)
            {
               // delay the object creation to demonstrate the thread saftey.
               Thread.Sleep(1500);
            _instance =new Singleton();
            }
      return     _instance;
  }
 }
}

Run the above class using Main method shown below, you can notice Singleton constructor is called twice by the both threads, since it is not thread safe. ( You can use the same Main methid implementation for all 3 Singleton implementations)

Main method implementation

class Program
{
staticvoid Main(string[] args)
{
new Thread(() => { Singleton sin1 = Singleton.SingletonInstance; }).Start();
Singleton sin2 = Singleton.SingletonInstance;
 
Console.ReadKey();
}
}

Singleton thread safe

Making the above implementation to a thread safe code is not a complex task, we can use our same old locking technique.

class Singleton
{
privatestatic Singleton _instance;
privatestaticobject _lock =newobject();
 
private Singleton()
{
Console.WriteLine(Singleton instantiated);
}
 
publicstatic Singleton SingletonInstance
{
get
{
lock (_lock)
{
if (_instance ==null)
  {
      // delay the object creation to demonstrate the thread saftey.
        Thread.Sleep(1500);
         _instance =new Singleton();
   }
return _instance;
}
}
}
}

The above is a perfect Singleton implementation in C#. But is there any other way that we can have the Singleton behavior without compensating our performance into locking. Because locking is a performance drop for sure.

Singleton C# way  – The trendy way

This is a neat and a trendy way to implement the Singleton.

We do not use locks in this implementation and it is very fast yet purely thread safe.

class Singleton
{
    privatestaticreadonly Singleton _instance;
 
    static Singleton()
    {
             _instance =new Singleton();
     }
 
    private Singleton()
   {
       Console.WriteLine(Singleton instantiated);
    }
 
   public static Singleton SingletonInstance
  {
     get
    {
      return _instance;
     }
  }
}

The magic is, static constructor.

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

To remeber simply you can think that the static constructor is called when the class is loaded.

More about static constructors in this MSDN article.

Asynchronous Programing C# 5.0

C# 5.0 mostly bluff about the asynchronous programming. Of course it has some really kick ass features in the asynchronous programming world.

First of all, asynchronous programing is not new in C# 5.0. It’s been there from C# 1.0, so what’s the big deal now ?

In C# 5.0 they have created a whole new, very tidy and easy programing approach in asynchronous programing. It’s really very tidy.

Here’s a WPF sample application which downloads the headers of an HTTP request and displays in a TextBox. Simply we all know that if we do this without threads our UI will hang until the download operation completes. The solution we’ve been using is threading.

Here I want to make a point; conceptually we all know that using the threads for the above problem will yield the solution for UI unresponsiveness.  But it creates challenges like monitoring the threads and updating the UI, handling exceptions and code untidiness.

Again one more point, when using the threads for the above problem .NET provides various solutions. In Win Forms using the BackgroundWorker is the popular way, in WPF we go for the Dispatcher, we also have our same old IAsyncCallback and delegates mechanism, using the thread pool explicitly, creating and customizing our own threads.

As you see, almost all the above methods are cluttered every where, developers use their own way to handle the problem, not bad but it’s not good either.

And also we have our problems in updating the UI; especially when updating a UI control from a different thread. We get the Cross thread access exceptions.

Here’s the code that shows one way of how the above scenario can be implemented prior to C# 5.0 in WPF.

 private void OldAsyncTechnique()
        {
            SynchronizationContext sync = SynchronizationContext.Current;

            var req = (HttpWebRequest)WebRequest.Create("https://thuruinhttp.wordpress.com");
            req.Method = "HEAD";

            req.BeginGetResponse((asyncResult) =>
            {
                var resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
                sync.Post(delegate
                {
                    TxtHeaders.Text = FormatHeaders(resp.Headers);
                }, null);
            }, null);
        }

Here I get the SynchronizationContext of the current thread, (means the main UI thread) and creates my web request. Then I call the asynchronous BeginGetResponse method of the HttpWebRequest class.

To make the code compact, I called the EndGetResponse in lamda. Using the SynchronizationContext of the UI thread I post the message to the UI control.

But this very complex and I have to pass state object parameters and all. (I have passed null here).

Note : This is not the only way to do this.

 

In C# 5.0 we have new keywords async and await. (You still can enable this in .NET 4 by installing the Async CTP, but since the VS 2012 and .NET 4.5 is released do not waste your time on doing this. You can simply upgrade yourself to .NET 4.5 world)

Here’s the code.

 private async void NewMethod()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://thuruinhttp.wordpress.com");
            req.Method = "HEAD";
            HttpWebResponse res = (HttpWebResponse) await req.GetResponseAsync();
            TxtHeaders.Text = FormatHeaders(res.Headers);
        }

Simple as that. You declare the method async and make an awaitable type.

When the code hits the await keyword the method returns immediately, and once the await got the results, the method begins the execution from where it left. Simple theory.

But how it is possible, again that is simple inside C# when you compile the above code, C# compiler rewrites the above code in a fine and an efficient old way.

The real working pattern and how things happen are complex and it used the TPL heavily.

Important : Once you install .NET 4.5 you will get the GetResponseAsync() in the WebClient class. And most classes are enriched with these types of async methods in .NET 4.5. We can have our async and await functionality in our custom classed as well.

Here’s the implementation of the FormatHeaders method.

 private string FormatHeaders(WebHeaderCollection collection)
        {
            StringBuilder builder = new StringBuilder();
            foreach (var s in collection.Keys)
            {
                builder.Append(s + " : ");
                builder.Append(collection[s.ToString()].ToString());
                builder.Append(Environment.NewLine);
            }

            return builder.ToString();
        }