//public static Singleton singletonCommon = new Singleton();//只构造一个对象 static void Main(string[] args) { try { Console.WriteLine("欢迎来到.net高级班公开课之设计模式特训,今天是Eleven老师为大家带来的单例模式Singleton"); ////Singleton singleton = Singleton.CreateInstance(); //new Singleton();//只构造一个对象 ////for (int i = 0; i < 10; i++) ////{ //// Singleton singleton = Singleton.CreateInstance(); //// Singleton singleton = new Singleton();//每次都构造一个对象 //// singletonCommon.Show(); //// singleton.Show(); ////} ////StudentA.UseSingleton(); ////StudentB.UseSingleton(); ////StudentC.UseSingleton(); List <IAsyncResult> resultList = new List <IAsyncResult>(); 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(); }
/// <summary> /// 静态字段在程序进程只有一个 /// </summary> //public static Singleton singleton = new Singleton(); static void Main(string[] args) { try { SingletonSecond second = SingletonSecond.CreateInstance(); SingletonThird third = SingletonThird.CreateInstance(); //Singleton singleton = new Singleton(); //对象的重用 TaskFactory taskFactory = new TaskFactory(); List <Task> taskList = new List <Task>(); //for (int i = 0; i < 50000; i++) //{ // taskList.Add(taskFactory.StartNew(() => // { // Singleton singleton = Singleton.CreateInstance();// new Singleton(); // singleton.Show();//多线程去运行同一个实例的同一个方法 // })); //} for (int i = 0; i < 50000; i++) { taskList.Add(taskFactory.StartNew(() => { SingletonSecond singleton = SingletonSecond.CreateInstancePrototype();// new Singleton(); singleton.Show(); })); } Task.WaitAll(taskList.ToArray()); Console.WriteLine("第一轮全部完成"); //for (int i = 0; i < 5; i++) //{ // taskList.Add(taskFactory.StartNew(() => // { // Singleton singleton = Singleton.CreateInstance();// new Singleton(); // //singleton.Show(); // })); //} //0 1 50000 还是接近50000 Console.WriteLine(SingletonSecond.CreateInstancePrototype().iTotal); //for (int i = 0; i < 5; i++) //{ // taskFactory.StartNew(() => // { // Singleton singleton = Singleton.CreateInstance();// new Singleton(); // singleton.Show(); // }); //} //OtherClass.Show(); //OtherClass.Show(); //OtherClass.Show(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); }