Wednesday, June 1, 2016

Thread-safe Singleton Pattern (Multi-threaded Singleton Pattern)

In my previous post Singleton Pattern, I explained various ways to implement singleton pattern but those were not thread-safe. In multi-threaded environment it’s quite possible that multiple thread enters into Instance property at the same time and more than one object of Singleton class may be created. In this article I'll show you various ways to create thread-safe singleton pattern.

Simple version of thread-safe singleton pattern via locking.


Code -
public sealed class Singleton
{
    //private static member.
    private static Singleton instance;
    private static object objLock = new object();

    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }

    //This static property responsible for creation of instance of this class.
    public static Singleton Instance
    {
        get
        {
            lock (objLock)
            {
                if (instance == null)
                {
                    Console.WriteLine("New Instance created");
                    instance = new Singleton();
                }
            }
            return instance;
        }
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}


class Program
{
    static void Main(string[] args)
    {
        //array of threads
        Thread[] thrd = new Thread[4];

        for (int i = 0; i < 4; i++)
        {
            thrd[i] = new Thread(new ThreadStart(() =>
            {
                Singleton singleObject = Singleton.Instance;
                singleObject.Display();
            }));
            thrd[i].Start();
        }
        Console.Read();
    }
}
  

Output – 

You can see “New Instance created” message displayed only once since new instance created only once across multiple thread calls. The above example allows only single thread to enter instance creation code when no instance created. The lock block allows only single thread to enter and create an instance. 

In this approach lock is acquired every time the instance of class is requested by user so it will impact performance. To avoid an exclusive locking in every call of Instance property, you can use double-check locking approach.

Double-check locking approach


Code –
public sealed class Singleton
{
    //private static member.
    private static volatile Singleton instance;
    private static object objLock = new object();

    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }

    //This static method responsible for creation of instance of this class.
    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (objLock)
                {
                    if (instance == null)
                    {
                        Console.WriteLine("New Instance created");
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}
   
class Program
{
    static void Main(string[] args)
    {
        //array of threads
        Thread[] thrd = new Thread[4];

        for (int i = 0; i < 4; i++)
        {
            thrd[i] = new Thread(new ThreadStart(() =>
            {
                Singleton singleObject = Singleton.Instance;
                singleObject.Display();
            }));
            thrd[i].Start();
        }
        Console.Read();
    }
}

Output - 

Same as above example.

In double-check locking approach, Only first thread acquires lock and creates object while other threads will not be able to acquire lock since I added check before lock statement. So this way we can reduce acquiring lock for each and every thread who calls Instance property and improve performance. I have declared instance variable as volatile so it will read from physical memory every time instead of thread's internal cache.

Thread-safe without using locks via static initialization


As per above example, we can implement thread-safe singleton pattern using locks but there is another way to create thread-safe singleton pattern without using locks but via static member initialization. This approach does not support lazy initialization of an object like above example does.

Code –
namespace ThreadSafeSingleton
{
    public sealed class Singleton
    {
        private static Singleton instance = new Singleton();
       
        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }

        public void Display()
        {
            Console.WriteLine("Display Method called from Singleton Class...");
        }
    }
}

namespace ThreadSafeSingleton
{
    class Program
    {
        static void Main(string[] args)
        {
            //array of threads
            Thread[] thrd = new Thread[4];

            for (int i = 0; i < 4; i++)
            {
                thrd[i] = new Thread(new ThreadStart(() =>
                {
                    Singleton singleObject = Singleton.Instance;
                    singleObject.Display();
                }));
                thrd[i].Start();
            }
            Console.Read();
        }
    }
}

Output – 









With this approach, new instance is created only once when any static member or method of this class is referenced. This uses static variable initializer approach and CLR takes care of it. In this approach you have very less control over the creation of the object.

Hope this article helps you to understand different ways to implement thread-safe singleton pattern. Please leave your feedback.

References –

See Also – 


Tuesday, May 31, 2016

Singleton Pattern


Singleton pattern ensures a class can have only single instance during the lifetime of an application.

When to use Singleton Pattern?

When you want to create single object only once during application life you can go with Singleton Pattern. The implementation and use of singleton pattern is very easy. See below example.

Code –
public class Singleton
{
    //private static member.
    private static Singleton instance;
   
    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }
   
    //This static method responsible for creation of instance of this class.
    public static Singleton GetInstance()
    {
        //create new instance only in first call, rest of the time it will return existing object
        if (instance == null)
            instance = new Singleton();

       return instance;
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Singleton singleObject =  Singleton.GetInstance();
        singleObject.Display();
        Console.Read();
    }
}

Output –



Another way (via Property) to implement singleton pattern.


public class Singleton
{
    //private static member.
    private static Singleton instance;

    //Private constructor prevents instance creation of class from outside.
    private Singleton() { }

    //This static method responsible for creation of instance of this class.
    public static Singleton Instance
    {
        get
        {
            //create new instance only in first call, rest of the time it will return existing object
            if (instance == null)
                instance = new Singleton();

            return instance;
        }
    }

    public void Display()
    {
        Console.WriteLine("Display Method called from Singleton Class...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Singleton singleObject = Singleton.Instance;
        singleObject.Display();
        Console.Read();
    }
}

Output –

Same as above example.

Advantages - 

  • Class can perform additional functionalities other than creation of an object.
  • This is referred as Lazy Initialization approach since instance of an object is not created until user call instance property or method. This approach avoids instantiating singletons class when application starts.

Disadvantage -

  • Singleton pattern is not thread safe by default. You need to write additional code to make it thread safe. I'll post article for Thread safe singleton pattern in few days.

Hope you liked this article. Please leave your feedback.

References –


See Also –

Monday, October 15, 2012

Visual Studio not automatically building application on pressing F5 key


Recently I was facing one issue with Visual Studio 2010. When I change some code in Visual Studio 2010 and hit F5, it is not building application and running old compiled version. Every time I want to debug an application, I have to first manually build application and then hit F5  key to debug my application. Usually visual studio automatically builds application on hitting F5 key.

I found interesting solutions from internet to resolve this issue. You need to open the Configuration Manager from Debug Dropdown or right click on Solution and open Configuration Manager Window. Now click on Build Checkbox.


Another solution would be useful if your Project is out of date or you have installed newer version. Go to Tool -> Option -> Project and Solutions -> Build and Run from Visual Studio. Now select “Always build” or “Prompt to build” option of “On Run, when project are out of date”.


Hope this small Tip might help you to fix this issue.

See Also –

Sunday, October 14, 2012

How to get list of System Colors in WPF


You might aware about available System Colors in Windows machine. You might have changed system colors using below window. If you change color and appearance of any item (e.g. color, font, size, font color etc.) it will change appearance and color of all the application available in windows. In short you can change system’s default appearance and color using below dialog.


In this post I will demonstrate how you can get available list of system colors dynamically using WPF application. Let’s have a look on below example.

XAML
<Window x:Class="WpfApplication1.SysColors"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="System Colors" Height="300" Width="300">
<Grid>
<DataGrid Name="grdSysColorList"
          AutoGenerateColumns="False"
          GridLinesVisibility="Vertical">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Color"
                                Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Margin="5">
                        <TextBlock.Background>
                            <SolidColorBrush Color="{Binding Color}" />
                        </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Name"
                            Binding="{Binding Name}"
                            Width="200"/>
    </DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

Code
public partial class SysColors : Window
{
public SysColors()
{
    InitializeComponent();
    LoadSystemColors();
}
public void LoadSystemColors()
{
    List<SysColorItem> sysColorList = new List<SysColorItem>();
    Type t = typeof(System.Windows.SystemColors);
    PropertyInfo[] propInfo = t.GetProperties();
    foreach (PropertyInfo p in propInfo)
    {
        if (p.PropertyType == typeof(Color))
        {
            SysColorItem list = new SysColorItem();
            list.Color = (Color)p.GetValue(new Color(),
                BindingFlags.GetProperty, null, null, null);
            list.Name = p.Name;

            sysColorList.Add(list);
        }
        else if (p.PropertyType == typeof(SolidColorBrush))
        {
            SysColorItem list = new SysColorItem();
            list.Color = ((SolidColorBrush)p.GetValue(new SolidColorBrush(),
                BindingFlags.GetProperty, null, null, null)).Color;
            list.Name = p.Name;

            sysColorList.Add(list);
        }
    }
    grdSysColorList.ItemsSource = sysColorList;
}
}

public class SysColorItem
{
public string Name { get; set; }
public Color Color { get; set; }
}
}

Output


In above example you can see DataGrid having two columns Color and Name. Color displays various system colors and name displays its name. I have retrieved this system colors using Reflection. First I have retrieved type of SystemColors and then retrieved all the properties having Color and SolidColorBrush type. In last i have bind that list of SystemColors to DataGrid.


How to apply system colors to WPF controls

In above example we saw how we can retrieve list of system colors dynamically. Now let’s see how you can apply system colors to WPF control.

<Button Background="{x:Static SystemColors.MenuHighlightBrush}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">



Above code demonstrates how you can apply MenuHighlightBrush to Button’s background. Similarly you can apply other system colors as well. SystemColors has all the colors defined as Static property so we have used {x:Static} markup to retrieve system color.

As per above example, if your application running and MenuHighlightBrush color is changed in background then your application will not display newly changed color. If you want to do so you can use DynamicResource markup. DynamicResource will update resources dynamically whenever it changed while your application is running. Let’s have a look on below code snippet which used DynamicResource.

<Button Background="{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
</Button>

In above code I have used DynamicResource markup to display resources dynamically. If MenuHighlightBrushKey changed in background then your application will display newly changed value.

Here one thing to noticed that I have used resource key in second example while in first example I have used brush. The reason behind that is DynamicResource markup uses resource key.

Hope you liked this post. You can checkout below link to know more about System Colors in WPF.
http://blogs.msdn.com/b/wpf/archive/2010/11/30/systemcolors-reference.aspx

See also –