Tuesday, April 21, 2009

The perfect c# singleton

Hi,
after several tries i got the perfect thread safety c# singleton

public class DbProxy
{
private static DbProxy _oInstance = null;
private static readonly object padlock = new object();

// @@@ public "consructor"
public static DbProxy Instance
{
get
{
if (DbProxy._oInstance == null)
{
lock (padlock)
{
if (DbProxy._oInstance == null)
{
DbProxy newDB = new DbProxy();
System.Threading.Thread.MemoryBarrier();
DbProxy._oInstance = newDB;
}
}
}
return DbProxy._oInstance;
}
}
// @@@ private constructor
private DbProxy()
{

}
}


3 comments:

Sandeep Aparajit said...

Thanks for the singleton class Yosi. Usually we tend to miss the MemoryBarrier statement, which causes issues on the production server environment.

Yosi Havia said...

what issues does it cause?

Erich said...

Note that, using static variables, your instances may be thread-safe, but they're not request-safe, since static variables have too large a scope (per-application, not per-request). You can't use it for web applications.