C# AutoResetEvent / ManualResetEvent

博客介绍了在不同线程间创建可共享的bool量,类似旗标。着重讲解了AutoResetEvent和ManualResetEvent,前者常用于两线程间信号发送,线程可通过WaitOne()等待、Set()取消等待、reset()恢复;后者使用效果类似,但状态变化机制不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人理解这个应该就相当于一个旗标,在不同线程之间创建一个都可以使用的bool量

AutoResetEvent 常常被用来在两个线程之间进行信号发送,两个线程共享相同的AutoResetEvent对象,线程可以通过调用AutoResetEvent对象的WaitOne()方法进入等待状态,waitone可以有一个等待时间参数,然后另外一个线程通过调用AutoResetEvent对象的Set()方法取消等待的状态,通过reset()恢复

class Program
    {
        const int count = 10;
        //赋值为false也就是没有信号
        static AutoResetEvent myResetEvent = new AutoResetEvent(false);
        static int number;
        static void Main(string[] args)
        {
            Thread thread = new Thread(funThread);
            thread.Name = "QQ";
            thread.Start();
            for (int i = 1; i < count; i++)
            {
                Console.WriteLine("first number: {0}",i);
                number = i;
                //这里是设置为有信号
                myResetEvent.Set();
                Thread.Sleep(2000);
            }
            thread.Abort();
        }

        static void funThread()
        {
            while (true)
            {
                //执行到这个地方时,会等待set调用后改变了信号才接着执行
                myResetEvent.WaitOne();
                Console.WriteLine("end {0} number: {1}", Thread.CurrentThread.Name, number);
            }
        }

    }

ManualResetEvent的使用和效果和AutoResetEvent是一样的,不同的是AutoResetEvent set后,当某个线程里有waitone接受后,autorestevent又变成set之前的状态,即其他线程的waitone仍在等待,而manualrestevent set之后,其他线程的waitone都不在等待,除非手动调用manualresetevent的Reset()。

参考:
https://www.cnblogs.com/fangyz/p/5040206.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值