C# 多线程交替按照指定顺序执行

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。

 

C# 多线程交替按照指定顺序执行_第1张图片

你可能感兴趣的:(多线程的应用,开发语言,c#)