How do you call AutoResetEvent in C#?

The AutoResetEvent class is a synchronization event class used for thread synchronization in multi-threading. In C#, you can access its methods and properties through an instance of AutoResetEvent.

Here is a basic example using the AutoResetEvent class:

using System;
using System.Threading;

class Program
    static AutoResetEvent autoResetEvent = new AutoResetEvent(false);

    static void Main()
        Thread t1 = new Thread(Worker);

        // 等待子线程执行完成

        Console.WriteLine("Main thread is done.");

    static void Worker()
        Console.WriteLine("Worker thread is starting...");
        Thread.Sleep(2000); // 模拟耗时操作

        Console.WriteLine("Worker thread is done.");

        // 通知主线程完成

In the above example, first an AutoResetEvent instance autoResetEvent is created and initialized as false. Then a child thread t1 is created and the Worker method is called, which simulates a time-consuming operation. After the operation is finished, the main thread is notified of completion by calling the Set() method of autoResetEvent. The main thread will be blocked when calling the WaitOne() method until autoResetEvent is set to true.

Through this approach, synchronization and communication between threads can be achieved.


More tutorials

How can concurrent programming be implemented in Python?(Opens in a new browser tab)

Java Thread Join method(Opens in a new browser tab)

multithreading in Java that you need to know(Opens in a new browser tab)

The main method in Java(Opens in a new browser tab)

How is WinForms implemented in C#?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *