多线程(CountdownEvent)

c#的CountdownEvent 对线程控制 https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.countdownevent?view=netcore-2.1

通过 init一个初始化的计数器来管理线程,通过.Signal()让计算器减1,知道计数是0时结束wait.



using System;

using System.Threading;

using staticSystem.Threading.Thread;

using staticSystem.Console;

namespacecountdownEvent

{

    class Program

    {

        static CountdownEvent _countdown = newCountdownEvent(2);//initial count

        static void PerformOperaton(stringmessage,int secouds)

        {

            WriteLine("Beforesleep:"+CurrentThread.Name);

            WriteLine("Beforesingal:" + _countdown.CurrentCount);

           Sleep(TimeSpan.FromSeconds(secouds));

            WriteLine(message);

            WriteLine("Aftersleep:"+CurrentThread.Name);

            _countdown.Signal(); // count -1

            WriteLine("After singal:"+ _countdown.CurrentCount);

        }

        static void Main(string[] args)

        {

            Console.WriteLine("Start twooperations!");

            var t1 = new Thread(() =>PerformOperaton("Operation 1 is completed",4));

            var t2 = new Thread(()=>PerformOperaton("Operation 2 is completed!",8));

            t1.Name = "t1";

            t2.Name = "t2";

            t1.Start();

            t2.Start();

            _countdown.Wait();//util to 0;

           WriteLine("Both operations has beencompleted!");

            _countdown.Dispose();

        }

    }

}



输出结果:

Start twooperations!

Before sleep:t2

Before sleep:t1

Before singal:2

Before singal:2

Operation 1 iscompleted

After sleep:t1

After singal:1

The thread 14396 hasexited with code 0 (0x0).

Operation 2 iscompleted!

After sleep:t2

After singal:0

The thread 9520 hasexited with code 0 (0x0).

Bothoperations has been completed!




猜你喜欢

转载自blog.csdn.net/u010676526/article/details/80000670