首頁 >後端開發 >C#.Net教程 >c# 中CountDownEvent的使用

c# 中CountDownEvent的使用

黄舟
黄舟原創
2017-03-01 10:50:532419瀏覽

c# 中CountDownEvent的使用

class Program
    {
        static CountdownEvent _count = new CountdownEvent(3);
        static void Main(string[] args)
        {
          
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("thread 1 complete");
                _count.Signal();
            });
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("thread 2 complete");
                _count.Signal();
            });
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine("thread 3 complete");
                _count.Signal();
            });

            Console.WriteLine("waiting tasks....");
            _count.Wait();
            Console.WriteLine("all task completed");


            Console.ReadKey();
        }
      
    }

使用TASK的waitAll可以达到同样的效果:

 var t1 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("thread 1 complete");
            
            });
           var t2 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("thread 2 complete");
            
            });
           var t3 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine("thread 3 complete");
             
            });
            Console.WriteLine("waiting tasks....");
            Task.WaitAll(t1, t2, t3);
            Console.WriteLine("all task completed");


            Console.ReadKey();

 以上是c# 中CountDownEvent的使用的內容,更多相關內容請關注PHP中文網(www.php.cn)!


#
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn