Complete C# Tutorial

AutoResetEvent & ManualResetEvent in C# โ€“ Master Thread Signaling!

Hey there, C# champion! ๐Ÿ‘‹ Ever wondered how to pause a thread and wait for a signal before it continues?

Thatโ€™s exactly what AutoResetEvent in Thread and ManualResetEvent in Thread do! ๐Ÿš€ These tools are super useful when you need threads to coordinate with each other.

Today, weโ€™ll break them down with real-world examples and easy-to-understand code. Letโ€™s go! ๐ŸŽฏ

๐Ÿš€ Why Do We Need AutoResetEvent and ManualResetEvent?

Imagine this:

  • You are waiting for a bus ๐ŸšŒ. The bus will arrive at any time, but you wonโ€™t move until it does. (This is like a thread waiting for a signal!)

  • Once the bus arrives, you and others start moving.

In multithreading, sometimes one thread needs to signal another thread to continue.

That’s where AutoResetEvent and ManualResetEvent help! ๐Ÿ’ก

๐Ÿ”„ What is AutoResetEvent in Thread?

๐Ÿ”น AutoResetEvent is like a one-time traffic signal.
๐Ÿ”น When a thread waits, it stops until another thread signals it to continue.
๐Ÿ”น Once the signal is received, AutoResetEvent automatically resets back to red.

ย 

โœ… Syntax of AutoResetEvent

				
					AutoResetEvent autoEvent = new AutoResetEvent(false);
				
			
  • false means the thread starts in a blocked state.
  • true means the thread starts in a signaled state.

๐Ÿ† Example 1: Using AutoResetEvent in Thread

Letโ€™s say Thread A is waiting, and Thread B will signal it to continue.

				
					using System;
using System.Threading;

class Program
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void WaitingThread()
    {
        Console.WriteLine("Thread A is waiting for a signal...");
        autoEvent.WaitOne(); // Wait until signaled
        Console.WriteLine("Thread A received the signal and continues...");
    }

    static void Main()
    {
        new Thread(WaitingThread).Start();

        Thread.Sleep(2000); // Simulate some delay
        Console.WriteLine("Thread B sends the signal!");
        autoEvent.Set(); // Signal Thread A
    }
}
				
			

โœ… Expected Output

				
					Thread A is waiting for a signal...
Thread B sends the signal!
Thread A received the signal and continues...
				
			

WaitOne() makes Thread A wait until another thread calls Set().

โšก What is ManualResetEvent in Thread?

  • ManualResetEvent is like a pedestrian crossing button. ๐Ÿšฆ
  • Once signaled, it stays green until reset manually.
  • Multiple threads can pass through without waiting until we reset it to red.

ย 

โœ… Syntax of ManualResetEvent

				
					ManualResetEvent manualEvent = new ManualResetEvent(false);
				
			

๐Ÿ† Example 2: Using ManualResetEvent in Thread

Letโ€™s say multiple threads are waiting, and one thread signals all of them at once.

				
					using System;
using System.Threading;

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

    static void WaitingThread()
    {
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is waiting...");
        manualEvent.WaitOne(); // Wait until signaled
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} received the signal!");
    }

    static void Main()
    {
        for (int i = 0; i < 3; i++)
        {
            new Thread(WaitingThread).Start();
        }

        Thread.Sleep(2000); // Simulate delay
        Console.WriteLine("Main thread sends the signal!");
        manualEvent.Set(); // Signal all threads

        Thread.Sleep(2000);
        Console.WriteLine("Resetting the signal...");
        manualEvent.Reset(); // Reset so future calls must wait
    }
}
				
			

โœ… Expected Output

				
					Thread 3 is waiting...
Thread 4 is waiting...
Thread 5 is waiting...
Main thread sends the signal!
Thread 3 received the signal!
Thread 4 received the signal!
Thread 5 received the signal!
Resetting the signal...
				
			
  • All threads continue when Set() is called.
  • New threads must wait after Reset().

๐Ÿค” AutoResetEvent vs ManualResetEvent โ€“ Whatโ€™s the Difference?

FeatureAutoResetEventManualResetEvent
Signal BehaviorResets automaticallyStays signaled until manually reset
Threads UnblockedOnly one threadAll waiting threads
Best Use CaseOne-time signal for a threadSignaling multiple threads

๐Ÿšฆ Use AutoResetEvent when only one thread needs the signal.
๐Ÿ“ข Use ManualResetEvent when multiple threads need the signal at once.

๐ŸŒ Real-World Example: Loading Data Before Execution

Letโ€™s say youโ€™re building a game ๐ŸŽฎ.

  • The main thread needs to wait until assets are loaded before starting the game.

  • Multiple worker threads are loading assets in the background.

ย 

โœ… Code for Real-World Example

				
					using System;
using System.Threading;

class GameLoader
{
    static ManualResetEvent assetsLoaded = new ManualResetEvent(false);

    static void LoadAssets()
    {
        Console.WriteLine($"Loading assets... (Thread {Thread.CurrentThread.ManagedThreadId})");
        Thread.Sleep(3000); // Simulate loading time
        Console.WriteLine("Assets loaded!");
        assetsLoaded.Set(); // Signal that loading is complete
    }

    static void StartGame()
    {
        Console.WriteLine("Waiting for assets to load...");
        assetsLoaded.WaitOne(); // Wait for assets to be ready
        Console.WriteLine("Game is starting!");
    }

    static void Main()
    {
        new Thread(LoadAssets).Start();
        new Thread(StartGame).Start();
    }
}
				
			

โœ… Expected Output

				
					Waiting for assets to load...
Loading assets... (Thread 3)
Assets loaded!
Game is starting!
				
			

Game starts only after assets are loaded!

๐ŸŽฏ Conclusion โ€“ Why This is Important?

โœ… AutoResetEvent in Thread is great for one-time signals.
โœ… ManualResetEvent in Thread is perfect when multiple threads need the signal.
โœ… These tools help coordinate threads efficiently.

ย 

๐Ÿš€ Next What?

๐ŸŽ‰ Awesome work! You now understand AutoResetEvent in Thread and ManualResetEvent in Thread!

But wait, thereโ€™s more! ๐Ÿš€

Next up: Reader-Writer Locks in Threads โ€“ Optimize Multithreading Performance! Stay tuned! ๐Ÿ”ฅ

Leave a Comment

Share this Doc

AutoResetEvent and ManualResetEvent

Or copy link