AutoResetEvent的简单理解

本文通过一个游戏柄轮换的示例,详细介绍了AutoResetEvent的基本用法。使用一个AutoResetEvent对象控制两个线程间的切换,演示了如何在C#中实现线程同步。

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

努力的成为一名牛逼的女程序员!


这段时间有接触到AutoResetEvent,在自己简单理解之后,做了个小demo,介绍下基本用法,欢迎大家指正!

说明:

  1. 网上很多都是用了两个AutoResetEvent对象来模拟,我这里用一个。
  2. 每次交换用10秒钟来间隔,以便看清过程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoResetEventTest
{
    class Program
    {
        private static AutoResetEvent autoResetEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            var playtime = 10;
            Console.WriteLine("两个游戏柄坏了其中一只,A和B只能各玩一会...");
            var t = new Thread((() => Process(playtime)));
            t.Start();
            Console.WriteLine("B先玩,A开始等待...");
            autoResetEvent.WaitOne();

            Console.WriteLine("A获得了游戏柄");
            Console.WriteLine("A开始第二局,B开始等待...");
            Thread.Sleep(TimeSpan.FromSeconds(playtime));
            autoResetEvent.Set();
            autoResetEvent.WaitOne();
            Console.WriteLine("A获得了游戏柄");
            Console.WriteLine("A关掉电源,游戏结束...");
            Console.ReadKey();
        }

        static void Process(int seconds)
        {
            Console.WriteLine("B开始玩第一局...");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("第一局结束,B把手柄给A");
            autoResetEvent.Set();
            autoResetEvent.WaitOne();

            Console.WriteLine("第二局结束,A把手柄给B");
            Console.WriteLine("B开始玩第三局...");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("第三局结束,B把手柄给A");
            autoResetEvent.Set();
        }
    }
}

附上结果图:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值