C# AutoResetEvent 理解
2024-09-03 07:07:09
、、
AutoResetEvent在内存中保持着一个bool值
值为False,则使线程阻塞;值为True,使线程退出阻塞;
创建AutoResetEvent对象的实例,在函数构造中传递默认的bool值;
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
autoResetEvent.Reset(); //修改bool值为False;
autoResetEvent.Set(); //修改bool值为True;
--------------------------------------------------------------------
WaitOne() 方法,阻止 线程 继续执行,进入等待状态;收到信号返回true,否则返回false;
WaitOne(毫秒),等待指定秒数,如果指定秒数后,没有收到任何信号,那么后续代码将继续执行;
AutoResetEvent autoResetEvent = new AutoResetEvent(false);//只对一个线程设置为有信号。
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e){ }
private void buttonSet_Click(object sender, EventArgs e)
{
autoResetEvent.Set();//设置为True 时 WriteMsg() 会跳出循环,停止输出:Continue;
}
private void buttonStart_Click(object sender, EventArgs e)
{
Thread td = new Thread(WriteMsg);
td.Start();
}
/// <summary>
/// 输出消息
/// </summary>
public void WriteMsg()
{
autoResetEvent.Set();
autoResetEvent.WaitOne();
//遇到此行代码,如果autoResetEvent为true,会直接往下执行代码,autoResetEvent为false,会停止在此行代码;
//因为此行代码之前,执行了Set()方法,所以WaitOne()语句直接执行过。
textBox1.AppendText("\r\nvvvvvvv");
//此时,autoResetEvent 变成 false ;
while (!autoResetEvent.WaitOne(TimeSpan.FromSeconds()))//原值为:false,加上!号变为:true ;
{
textBox1.AppendText("\r\nContinue");
Thread.Sleep(TimeSpan.FromSeconds());
}
bool bl10 = autoResetEvent.WaitOne();
//跳出循环后,执行到此行代码时,因为autoResetEvent又变为false,所以就停止在了此处,没有继续执行。
//再次执行autoResetEvent.Set();方法后就会直接执行完成方法。
}
private void buttonReset_Click(object sender, EventArgs e)
{
autoResetEvent.Reset();
}
---------------------------------------------------------------------
/// <summary>
/// 输出消息
/// </summary>
public void WriteMsg()
{
autoResetEvent.WaitOne(TimeSpan.FromSeconds());
//如果没有Reset() 和 Set()方法被调用,当执行到此行代码时,会等待5秒钟,才会继续执行后面的代码;
//如果执行了.Set()方法,就会立马继续执行后面代码,不会继续等待5秒之后。
textBox1.AppendText("\r\nContinue");
Thread.Sleep(TimeSpan.FromSeconds());
}
‘’
最新文章
- Oracle RAC客户端tnsnames.ora相关配置及测试
- CPU的栈机制的一个小问题
- #!/usr/bin/env python与#!/usr/bin/python的区别
- 50ms延时程序
- JSP中显示用户信息
- 密码有效性验证失败。该密码不够复杂,不符合 Windows 策略要求
- C++第13周(春)项目1 - 点、圆的关系
- Java回调机制解读
- ITU-T G.1081 IPTV性能监测点 (Performance monitoring points for IPTV)
- 图片与Base64的转换
- c# 中的封装、继承、多态详解
- Gym 100963B
- JavaEE学习之Spring AOP
- load 过高分析办法
- CSS背景与边框属性-----box-shadow
- 滚动条事件window.onscroll
- 微信小程序——<;radio>;<;/radio>;大小改变
- 磁共振中的T1, T2 和 T2*的原理和区别
- 安装和使用solr
- 神之编辑器emacs