方法一 :一个静态的对象创建方法
public class Singleton
{
private Singleton()
{
Thread.Sleep(1000);//耗时
string bigSize = "占用10M内存";//耗计算资源
string resource = "占用多个线程和数据库连接资源";//耗有限资源
Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name,
Thread.CurrentThread.ManagedThreadId);
}
private static Singleton _Singleton = null;
private static object Singleton_Lock = new object();
public static Singleton CreateInstance()
{
if (_Singleton == null)//保证对象初始化之后的所有线程,不需要等待锁
{
Console.WriteLine("准备进入lock");
lock (Singleton_Lock)//保证只有一个线程进去判断
{
//Thread.Sleep(1000);
if (_Singleton == null)//保证对象为空才真的创建
{
_Singleton = new Singleton();
}
}
}
return _Singleton;
}
public void Show()
{
Console.WriteLine("这里调用了{0}.Show", this.GetType().Name);
}
}
方法二 :私有化构造函数
public class SingletonSecond
{
private SingletonSecond()
{
Thread.Sleep(1000);//耗时
string bigSize = "占用10M内存";//耗计算资源
string resource = "占用多个线程和数据库连接资源";//耗有限资源
Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name,
Thread.CurrentThread.ManagedThreadId);
}
private static SingletonSecond _Singleton = null;
// 静态构造函数:由CLR保证,在第一次使用这个类之前,调用而且只调用一次
static SingletonSecond()
{
_Singleton = new SingletonSecond();
}
public static SingletonSecond CreateInstance()
{
return _Singleton;
}
public void Show()
{
Console.WriteLine("这里调用了{0}.Show", this.GetType().Name);
}
}
方法三: 静态变量
public class SingletonThird
{
private SingletonThird()
{
Thread.Sleep(1000);//耗时
string bigSize = "占用10M内存";//耗计算资源
string resource = "占用多个线程和数据库连接资源";//耗有限资源
Console.WriteLine("{0}被构造,线程id={1}", this.GetType().Name,
Thread.CurrentThread.ManagedThreadId);
}
// 静态变量:会在类型第一次使用的时候初始化,而且只初始化一次
private static SingletonThird _Singleton = new SingletonThird();
public static SingletonThird CreateInstance()
{
return _Singleton;
}
public void Show()
{
Console.WriteLine("这里调用了{0}.Show", this.GetType().Name);
}
}
static void Main(string[] args)
{
try
{
List resultList = new List();
resultList.Add(new Action(() =>
{
Singleton sin = Singleton.CreateInstance();
sin.Show();
}).BeginInvoke(null,null));
for (int i = 0; i < 10; i++)
{
resultList.Add( new Action(() =>
{
Singleton singleton = Singleton.CreateInstance();
singleton.Show();
}).BeginInvoke(null, null));//会启动一个异步多线程调用
}
while (resultList.Count(r => !r.IsCompleted) > 0)
{
Thread.Sleep(10);
}
for (int i = 0; i < 10; i++)
{
resultList.Add(new Action(() =>
{
SingletonSecond singleton = SingletonSecond.CreateInstance();
singleton.Show();
}).BeginInvoke(null, null));//会启动一个异步多线程调用
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
版权声明:本文由Contione原创出品,转载请注明出处!
暂无评论,大侠不妨来一发?