Saqib Ullah

BootStrapper Know How

  Home  |   Contact  |   Syndication    |   Login
  109 Posts | 1 Stories | 820 Comments | 15 Trackbacks

News



Article Categories

Archives

Post Categories

Blogging websites

Favourite Blogs

Private Links

Sites

In this blog I want to describe you three ways how to write singleton class that is thread safe.

First Class

public
sealed class TSSingleton
{
private static volatile TSSingleton instance = null
;
private static object syncObj = new object
();
// make the default constructor private,
// so that no can directly create it.
private
TSSingleton(){}
// public property that can only get
// the single instance of this class.
public static TSSingleton
Instance
{
get
{
// only create a new instance if one doesn't already exist.
if (instance == null
)
{
// use this lock to ensure that only one thread is access
// this block of code at once.
lock
(syncObj)
{
   if (instance == null
)
   instance = new TSSingleton
();
}
}
// return instance where it was just
// created or already existed.
return
instance;
}}
}

Second Class

sealed class MysingleTon

    // Static members are lazily initialized.
    // .NET guarantees thread safety for static initialization
 
   private static readonly MysingleTon instance = new MysingleTon(); 
   public static MysingleTon GetInstance()
   {
      return instance;
    }
 }

Thrid Class

sealed class Singleton
{
  private Singleton() { }
  public static readonly Singleton TheInstance = new Singleton();
}

I use last example of singleton class.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Monday, March 26, 2007 7:52 PM

Feedback

# re: Three Singleton Classes, but use only ONE. 4/4/2007 12:53 AM Murtaza
...very good post

P.S. - yeh rang barangi font kiun use kia hai aap ne, parhne me mushkil ho rahi hai.

# re: Three Singleton Classes, but use only ONE. 8/5/2007 7:53 AM gfax
Holistic piece of codes.....

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: