大家都知道引用类型对象除实例字段的开销外,还有两个字段的开销:类型指针和同步块索引 (SyncBlockIndex)。同步块索引这个东西比起它的兄弟类型指针更少受人关注,显得有点冷落,其实此 兄功力非凡,在CLR里可谓叱咤风云,很多功能都要借助它来实现。
接下来我会用三篇来介绍同步块索引在.NET中的所作所为。
既然本章副标题是从lock开始,那我就举几个lock的示例:
代码1
public class Singleton
{
private static object lockHelper = new object();
private static Singleton _instance = null;
public static Singleton Instance
{
get
{
lock (lockHelper)
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}
}
}
代码2
public class Singleton
{
private static Singleton _instance = null;
public static Singleton Instance
{
get
{
object lockHelper = new object();
lock (lockHelper)
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}
}
}