首页主机资讯c# autoresetevent如何设置

c# autoresetevent如何设置

时间2025-09-26 05:55:04发布访客分类主机资讯浏览389
导读:在C#中,AutoResetEvent是一个同步原语,用于在多个线程之间进行通信 using System; using System.Threading; class Program { static AutoResetEven...

在C#中,AutoResetEvent是一个同步原语,用于在多个线程之间进行通信

using System;
    
using System.Threading;


class Program
{
    
    static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
 // 初始状态为false

    static void Main()
    {
    
        Thread thread1 = new Thread(Thread1Method);
    
        Thread thread2 = new Thread(Thread2Method);
    

        thread1.Start();
    
        thread2.Start();
    

        thread1.Join();
    
        thread2.Join();

    }


    static void Thread1Method()
    {
    
        Console.WriteLine("Thread 1 is waiting for the AutoResetEvent.");
    
        autoResetEvent.WaitOne();
     // 等待事件被设置为true
        Console.WriteLine("Thread 1 has been signaled.");

    }


    static void Thread2Method()
    {
    
        Thread.Sleep(1000);
     // 让线程2睡眠1秒,以便在线程1之前执行
        Console.WriteLine("Thread 2 is signaling the AutoResetEvent.");
    
        autoResetEvent.Set();
 // 将事件设置为true
    }

}
    

在这个示例中,我们创建了一个名为autoResetEventAutoResetEvent实例,并将其初始状态设置为false。然后,我们创建了两个线程thread1thread2,分别执行Thread1MethodThread2Method方法。

Thread1Method中,我们使用autoResetEvent.WaitOne()等待事件被设置为true。在Thread2Method中,我们首先让线程睡眠1秒,然后使用autoResetEvent.Set()将事件设置为true。当事件被设置为true时,Thread1Method将继续执行。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c# autoresetevent如何设置
本文地址: https://pptw.com/jishu/708121.html
c# autoresetevent有哪些应用 c# autoresetevent怎样初始化

游客 回复需填写必要信息