手机移动端网站怎么做的,中国建设厅官方网站,网站上的二维码,石家庄做网站优化1.关于AutoResetEvent和ManualResetEvent的区别解释如下#xff1a;
AutoResetEvent和ManualResetEvent是.NET中的两个线程同步类。它们之间的主要区别在于其释放信号的方式以及对等待线程的影响。
AutoResetEvent的作用是在等待的线程被信号唤醒后#xff0c;将信号自动重…1.关于AutoResetEvent和ManualResetEvent的区别解释如下
AutoResetEvent和ManualResetEvent是.NET中的两个线程同步类。它们之间的主要区别在于其释放信号的方式以及对等待线程的影响。
AutoResetEvent的作用是在等待的线程被信号唤醒后将信号自动重置为非终止状态。也就是说当一个线程等待一个AutoResetEvent对象时一旦它收到信号并被唤醒AutoResetEvent对象会自动将自身状态重置为非终止状态以便其他线程可以继续等待。这样只有一个线程能够通过AutoResetEvent对象其他线程需要重新等待信号。
而对于ManualResetEvent一旦一个线程等待一个ManualResetEvent对象并收到信号唤醒后ManualResetEvent对象不会自动重置为非终止状态。也就是说ManualResetEvent对象会维持其终止状态直到调用Reset()方法将其重置为非终止状态才能再次触发等待的线程。这意味着多个线程可以同时通过ManualResetEvent对象并且不需要重新等待信号。
因此AutoResetEvent和ManualResetEvent的主要区别在于对等待线程的影响。AutoResetEvent只允许一个线程通过并且在线程收到信号后自动重置为非终止状态而ManualResetEvent允许多个线程通过并且在等待线程收到信号后保持其终止状态直至调用Reset()方法将其重置为非终止状态。
总结AutoResetEvent不需要Reset()方法唤醒后自动调用而ManualResetEvent需用用户手动触发。
多个线程按照顺序执行案例如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp2
{public partial class Form1 : Form{public Form1(){InitializeComponent();}AutoResetEvent A new AutoResetEvent(false); //实例化阻塞事件AutoResetEvent B new AutoResetEvent(false); //实例化阻塞事件AutoResetEvent C new AutoResetEvent(false); //实例化阻塞事件private void button1_Click(object sender, EventArgs e){A.Set();Task.Run(() {AA();});Task.Run(() {BB();});Task.Run(() {CC();});}private void AA(){for (int i 0; i 10; i){A.WaitOne();//等待信号Console.WriteLine(A);B.Set();}}private void BB(){for (int i 0; i 10; i){B.WaitOne();Console.WriteLine(B);C.Set();}}private void CC(){for (int i 0; i 10; i){C.WaitOne();Console.WriteLine(C);A.Set();}}}
}执行结果依次按照顺序输出abc。