/* * 单例模式,保证整个进程中对象只被实例化一次,常驻内存,根据这个特点:单例模式有三种写法 * 普通的类型是需要的时候初始化,使用完被GC回收,根静态不一样。 */ static void Main(string[] args) { #region 普通调用 //Singleton singleton = Singleton.CreateInstance();//创建一个单例对象 //for (int i = 0; i < 10; i++) //{ // Singleton singletonss = Singleton.CreateInstance(); // singletonss.Show(); //} #endregion #region 第一种写法:静态方法 多线程调用 //多线程测试调用,结果也是公用一个对象,只调用一次构造函数 //List<IAsyncResult> asyncResults = new List<IAsyncResult>(); //for (int i = 0; i < 5; i++) //{ // asyncResults.Add(new Action(() => // { // Singleton singleton = Singleton.CreateInstance(); // singleton.Show(); // }).BeginInvoke(null, null));//会启动一个异步多线程的调用 //} #endregion #region 第二种写法:静态构造单例 多线程调用 List <IAsyncResult> asyncResults = new List <IAsyncResult>(); for (int i = 0; i < 5; i++) { asyncResults.Add(new Action(() => { SingletonSecond singleton = SingletonSecond.CreateInstance(); singleton.Show(); }).BeginInvoke(null, null));//会启动一个异步多线程的调用 } #endregion #region 第三种写法:静态变量单例 多线程调用 //List<IAsyncResult> asyncResults = new List<IAsyncResult>(); //for (int i = 0; i < 5; i++) //{ // asyncResults.Add(new Action(() => // { // SingletonThird singleton = SingletonThird.CreateInstance(); // singleton.Show(); // }).BeginInvoke(null, null));//会启动一个异步多线程的调用 //} #endregion Console.ReadKey(); //Console.WriteLine("----------------------------"); }
static SingletonSecond() { _SingletonSecond = new SingletonSecond(); }
static SingletonSecond() { Singleton = new SingletonSecond(); Console.WriteLine($"创造了一个 SingletonSecond 的实例,the thread_id is {Thread.CurrentThread.ManagedThreadId}"); }
/// <summary> /// 1.静态构造函数:由CLR保证,在第一次使用这个类型之前,调用而且只调用一次 /// </summary> static SingletonSecond() { singleton = new SingletonSecond(); }