Пример #1
0
 public static SingleFirst CreateInstance()
 {
     if (_SingleFirst == null)  //为了不用等待
     {
         Console.WriteLine("等待....");
         lock (_Singlelock)            //保证只有一个线程进去,其余线程等待
         {
             if (_SingleFirst == null) //如果为空,则创建
             {
                 _SingleFirst = new SingleFirst();
             }
         }
     }
     return(_SingleFirst);
 }
Пример #2
0
        public override void Open()
        {
            Console.WriteLine("******************************************************************");

            //单例一
            {
                SingleFirst first = SingleFirst.CreateInstance();

                //单线程构造
                for (int i = 0; i < 10; i++)
                {
                    SingleFirst first1 = SingleFirst.CreateInstance();
                    first1.Show();
                }

                //多线程构造
                List <IAsyncResult> async = new List <IAsyncResult>();
                for (int i = 0; i < 10; i++)
                {
                    async.Add(
                        new Action(() =>
                    {
                        SingleFirst first1 = SingleFirst.CreateInstance();
                        first1.Show();
                    }).BeginInvoke(null, null));
                }
                Console.WriteLine("********************************************");
                while (async.Count(t => !t.IsCompleted) > 0)
                {
                    Thread.Sleep(1000);
                }

                for (int i = 0; i < 10; i++)
                {
                    async.Add(
                        new Action(() =>
                    {
                        SingleFirst first1 = SingleFirst.CreateInstance();
                        first1.Show();
                    }).BeginInvoke(null, null));
                }
            }

            //单例二
            {
                //SingleSecond second = SingleSecond.CreateInstance();

                //for (int i = 0; i < 10; i++)
                //{

                //    SingleSecond second = SingleSecond.CreateInstance();
                //    second.Show();
                //}
            }

            //单例三
            {
                //SingleThird third = SingleThird.CreateInstance();
                //third.Show();

                for (int i = 0; i < 10; i++)
                {
                    SingleThird third = SingleThird.CreateInstance();
                    third.Show();
                }
            }

            Console.WriteLine("******************************************************************");
            Console.ReadKey();
        }