c# ManualResetEvent WaitHandle 实现同步

//本文演示了ManualResetEvent 类的非静态set()、Reset()、WaitOne()和

//WaitHandle类的静态方法WaitAllWaitAll()

//它们用于线程间的同步控制。

//实现了如下功能:线程1(定时控制)通知线程2和线程3采集数据

//线程2和3数据采集完了,各自通知线程1情况。

//那么线程1收到了两个线程的通知,则进行下一轮采集

static void Main(string\[\] args)

{

const int numberOfFiles=2;

Console.WriteLine("Press any key to start");

Console.ReadKey();

var cancelToken = new CancellationTokenSource();

var random = new Random();

Console.WriteLine("Task started, press any key to stop...");

var manualResetEvent1 = new ManualResetEvent(false);

var manualResetEvent2 = new ManualResetEvent(false);

ManualResetEvent \[\] manualEvents = new ManualResetEventnumberOfFiles;

for (int i = 0; i < numberOfFiles; i++)

{

manualEventsi = new ManualResetEvent(false);

}

bool reached = true;

//线程1

Task.Factory.StartNew(() =>

{

while (!cancelToken.IsCancellationRequested)

{

if (reached)

{

manualResetEvent1.Set();

manualResetEvent2.Set();

Console.WriteLine("Start new turn-----------------------");

}

Thread.Sleep(300);

reached = WaitHandle.WaitAll(manualEvents,400,false);

manualEvents0.Reset();

manualEvents1.Reset();

}

});

//线程2

Task.Factory.StartNew(() =>

{

var num = random.Next(10, 15);

while (!cancelToken.IsCancellationRequested)

{

manualResetEvent1.WaitOne();

Thread.Sleep(200);

num = random.Next(10, 15);

Console.WriteLine($"Task1 is running, this is number {num} ");

manualResetEvent1.Reset();

manualEvents0.Set();

}

});

//线程3

Task.Factory.StartNew(() =>

{

var num = random.Next(5, 10);

while (!cancelToken.IsCancellationRequested)

{

manualResetEvent2.WaitOne();

Thread.Sleep(100);

num = random.Next(5, 10);

Console.WriteLine($"Task2 is running, this is number {num}");

manualResetEvent2.Reset();

manualEvents1.Set();

}

});

Console.ReadLine();

cancelToken.Cancel();

Console.WriteLine("task cancelled");

Console.ReadLine();

}

相关推荐
国家一级摸鱼选手1 小时前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库14 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc19 小时前
C# 发展历史
开发语言·c#
kyle~21 小时前
C# --- 反射
开发语言·c#
暴走约伯2 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316343 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船3 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261354 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船4 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
huaqianzkh5 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#