Two autoresetevent ready and set interchangebly,CountDownEvent decrement until to 0 to triiger the singal action

class TwoWaySingaling
{
    static EventWaitHandle ready = new AutoResetEvent(false);
    static EventWaitHandle go = new AutoResetEvent(false);
    static readonly object locker = new object();
    static string message;

    public static void TestWork()
    {
        new Thread(Work).Start();
        ready.WaitOne();
        lock(locker)
        {
            message = "First time Lock";
        }
        go.Set();             

        ready.WaitOne();
        lock (locker)
        {
            message = "Second time lock";
        }
        go.Set(); 

        ready.WaitOne();
        lock(locker)
        {
            message = null;
        }
        go.Set(); 
    }

    static void Work()
    {
        while(true)
        {
            ready.Set();
            go.WaitOne();
            lock(locker)
            {
                if(string.IsNullOrWhiteSpace(message))
                {
                    return;
                }
                Console.WriteLine(message);
            }
        }
    }
}

 static void Main(string[] args)
 {
     TwoWaySingaling.TestWork(); 
     PrintInfo();
 }

 

static void Main(string[] args)
{
    CountDownEventDemo(); 
    PrintInfo();
}

static CountdownEvent countDown = new CountdownEvent(3);

static void CountDownEventDemo()
{
    new Thread(PrintSomething).Start("Thread 1");
    new Thread(PrintSomething).Start("Thread 2");
    new Thread(PrintSomething).Start("Thread 3");
    countDown.Wait();
    Console.WriteLine($"{DateTime.Now.ToString("O")},All threads have completed!");
}

static void PrintSomething(object str)
{
    Console.WriteLine($"{DateTime.Now.ToString("O")},line:{28}, {str}");
    Thread.Sleep(1000);
    Console.WriteLine($"{DateTime.Now.ToString("O")} {str}");
    if(countDown.Signal())
    {
        Console.WriteLine($"{DateTime.Now.ToString("O")} The initialized CountDownEvent has been decreased to 0!");
    }
}

  

 

 

posted @ 2024-03-12 11:20  FredGrit  阅读(13)  评论(0)    收藏  举报