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();
 }
复制代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 @   FredGrit  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示