这篇文章主要介绍了C# ManualResetEvent用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
ManualResetEvent表示线程同步事件,可以对所有进行等待的线程进行统一管理(收到信号时必须手动重置该事件)
其构造函数为:
public ManualResetEvent (bool initialState);
参数 initialState 表示是否初始化,如果为 true,则将初始状态设置为终止(不阻塞);如果为 false,则将初始状态设置为非终止(阻塞)。
注意:如果其参数设置为true,则ManualResetEvent等待的线程不会阻塞。 如果初始状态为false, 则在Set调用方法之前, 将阻止线程。
它只有两个方法
//将事件状态设置为终止状态,从而允许继续执行一个或多个等待线程。
public bool Set ();
//将事件状态设置为非终止,从而导致线程受阻。
public bool Reset ();
//返回值:操作成功返回true,否则false
讲了这么多,看个例子理解一下
using System;
using System.Threading;
public class Example
{
// mre is used to block and release threads manually. It is
// created in the unsignaled state.
private static ManualResetEvent mre = new ManualResetEvent(false);
static void Main()
{
Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");
for (int i = 0; i <= 2; i++)
{
Thread t = new Thread(ThreadProc);
t.Name = "Thread_" + i;
t.Start(); //开始线程
}
Thread.Sleep(500);
Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
"\nto release all the threads.\n");
Console.ReadLine();
mre.Set();
Thread.Sleep(500);
Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
"\ndo not block. Press Enter to show this.\n");
Console.ReadLine();
for (int i = 3; i <= 4; i++)
{
Thread t = new Thread(ThreadProc);
t.Name = "Thread_" + i;
t.Start();
}
Thread.Sleep(500);
Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
"\nwhen they call WaitOne().\n");
Console.ReadLine();
mre.Reset();
// Start a thread that waits on the ManualResetEvent.
Thread t5 = new Thread(ThreadProc);
t5.Name = "Thread_5";
t5.Start();
Thread.Sleep(500);
Console.WriteLine("\nPress Enter to call Set() and conclude the demo.");
Console.ReadLine();
mre.Set();
// If you run this example in Visual Studio, uncomment the following line:
//Console.ReadLine();
}
private static void ThreadProc()
{
string name = Thread.CurrentThread.Name;
Console.WriteLine(name + " starts and calls mre.WaitOne()");
mre.WaitOne(); //阻塞线程,直到调用Set方法才能继续执行
Console.WriteLine(name + " ends.");
}
}
结果如下
再次按enter键将导致该示例调用Reset方法, 并启动一个线程, 该线程在调用WaitOne时将被阻止。 按enter键, 最后一次调用Set以释放最后一个线程, 程序结束。
如果还不是很清楚可以进行单步调试,这样就能明白了!
文章参考MSDN:ManualResetEvent Class
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
本文标题为:C# ManualResetEvent用法详解
- Unity3D实现渐变颜色效果 2023-01-16
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- c# 模拟线性回归的示例 2023-03-14
- Oracle中for循环的使用方法 2023-07-04
- 如何使用C# 捕获进程输出 2023-03-10
- Unity Shader实现模糊效果 2023-04-27
- user32.dll 函数说明小结 2022-12-26
- .NET CORE DI 依赖注入 2023-09-27