Could someone introduce an use case for AutoResetEvent.Reset() method ? When and why I would like to use this method ? I understand WaitOne and Set but this is quite unclear for me.
Yes the AutoResetEvent
will automatically reset it's state whenever a thread which is waiting on the event is signaled. However it's possible that a given event is no longer valid and no thread has waited on an AutoResetEvent
since it was originally set. In that scenario the Reset
method becomes useful
Looks like it's just inherited from EventWaitHandle. Probably more useful with the ManualResetEvent which also inherits from that class?
The method is inherited from the base class EventWaitHandle
and is used to (re)set an AutoResetEvent
to its "blocked" state.
Because AutoResetEvent
will automatically enter that state as soon as it's signalled, you'll typically never see this method used in code, but for other classes deriving from EventWaitHandle
it would be much more useful!
If the AutoResetEvent producer wants to clear the event, you would use Reset(). This way, you can safely "reset" the event without having to know if it's currently signaled. If the producer used WaitOne to "reset" it's own event, there is a risk that you could deadlock (i.e. never return since the event isn't signaled and the producer thread is blocked).
Reset:
Sets the state of the event to nonsignaled ,See EventWaitHandle Class
Sample,
using System;
using System.Threading;
namespace ThreadingInCSharp.Signaling
{
class Program
{
static EventWaitHandle _waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
//The event's state is Signal
_waitHandle.Set();
new Thread(Waiter).Start();
Thread.Sleep(2000);
_waitHandle.Set();
Console.ReadKey();
}
private static void Waiter()
{
Console.WriteLine("I'm Waiting...");
_waitHandle.WaitOne();
//The word pass will print immediately
Console.WriteLine("pass");
}
}
}
Using Reset,
using System;
using System.Threading;
namespace ThreadingInCSharp.Signaling
{
class Program
{
static EventWaitHandle _waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
//The event's state is Signal
_waitHandle.Set();
_waitHandle.Reset();
new Thread(Waiter).Start();
Thread.Sleep(2000);
_waitHandle.Set();
Console.ReadKey();
}
private static void Waiter()
{
Console.WriteLine("I'm Waiting...");
_waitHandle.WaitOne();
//The word will wait 2 seconds for printing
Console.WriteLine("pass");
}
}
}
You should use ManualResetEvent when using Reset(), as AutoResetEvent resets itself when a thread has become signaled.
© 2022 - 2024 — McMap. All rights reserved.