Understanding and using ManualResetEvent in C# learning

ManualResetEvent is a class used for thread synchronization, allowing one or more threads to wait until a certain event occurs. It has two states: triggered and untriggered. When the event is untriggered, all waiting threads will be blocked until the event is manually triggered. Once the event is triggered, the waiting threads will be awakened and continue execution.

Here are the main methods and properties of ManualResetEvent:

  1. Set(): Set the event state to triggered and wake up all waiting threads.
  2. Reset(): Set the event status to untriggered.
  3. WaitOne() method: Waits for the event to be triggered. If the event has already been triggered, it returns immediately; otherwise, the thread will be blocked until the event is triggered.
  4. WaitOne(timeout): Wait for the event to be triggered. If the event has already been triggered, return immediately; otherwise, the thread will be blocked until the event is triggered or until the timeout expires.

Here is an example of using ManualResetEvent:

using System;
using System.Threading;

class Program
{
    static ManualResetEvent manualResetEvent = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(Work);
        Thread thread2 = new Thread(Work);

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

        // 等待一段时间
        Thread.Sleep(2000);

        // 触发事件,唤醒等待的线程
        manualResetEvent.Set();

        // 等待线程执行完毕
        thread1.Join();
        thread2.Join();

        Console.WriteLine("All threads completed.");
        Console.ReadLine();
    }

    static void Work()
    {
        Console.WriteLine("Thread {0} waiting.", Thread.CurrentThread.ManagedThreadId);

        // 等待事件的触发
        manualResetEvent.WaitOne();

        Console.WriteLine("Thread {0} resumed.", Thread.CurrentThread.ManagedThreadId);
    }
}

In the example above, we created two worker threads, thread1 and thread2, and had them wait for the manualResetEvent event to be triggered. In the main thread, after waiting for 2 seconds, we manually triggered the manualResetEvent event. This caused the two worker threads to wake up, continue executing, and ultimately output “All threads completed.”

ManualResetEvent is very useful in multithreaded programming as it allows for synchronization and coordination between threads. It is important to note that once a ManualResetEvent is set, it will remain in the set state until we call the Reset() method to reset it to the unset state.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds