C# 多线程同步

1. AutoResetEvent类实现同步

  如果要手动阻塞,可以使用ManualResetEvent

 class Program
    {
        public static int target = 0; //主线程写
        public static int count = 10; //主线程写target 次数
        static AutoResetEvent autorest;
        /// <summary>
        /// 程序概述: 主线程写target变量,写完后子线程读target变量。实现线程同步工作
        /// 实现:子线程通过waitone()方法等待主线程消息,主线程更新target变量后,通过autoset.Set()方法通知waitone等待的线程执行。
        /// 由于resetEvent 声明的是AutoResetEvent,所以autoset不用手动设置 reset()方法,再一次阻塞线程,会自动阻塞。
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //默认阻塞
            autorest = new AutoResetEvent(false);
            Thread readthread = new Thread(new ThreadStart(ReadTarget));
            readthread.Start();
            for(int i=0; i<count; i++)
            {
                Console.WriteLine($"主线程写:target={i}");
                target = i;
                //通知阻塞线程放弃阻塞
                //autorest.Reset(); //继续阻塞线程;
                autorest.Set();
                Thread.Sleep(1000);
            }
        }
        
        //读方法
        static void ReadTarget()
        {
            Console.WriteLine("子线程开始");
            //Console.WriteLine(autorest.WaitOne());
            while (true)
            {
                autorest.WaitOne(); //阻塞
                Console.WriteLine($"子线程读取:target={target}");
                
            }
          
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值