Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the blocking state of AutoResetEvent or ManualResetEvent in C#?

Is it possible to check the blocking state for C# System.Threading.AutoResetEvent or System.Threading.ManualResetEvent before calling WaitOne() ?

like image 884
Patrik Avatar asked Feb 17 '12 09:02

Patrik


2 Answers

An EventWaitHandle doesn't have a "blocking state". It is set or reset, nothing else. And no, you cannot check that any other way than by calling WaitOne().

You can pass a 0 for the time-out argument to avoid blocking. That's often a very bad idea because it says nothing about the state of the event after the WaitOne() call returns. It might have changed a nanosecond after that. This causes a very nasty kind of bug called "threading race". A Heisenbug.

like image 82
Hans Passant Avatar answered Sep 28 '22 09:09

Hans Passant


Use

public virtual bool WaitOne(
    TimeSpan timeout
)

with timeout 0. According to MSDN it will return the state of the WaitHandle immediately.

like image 32
BlueM Avatar answered Sep 28 '22 11:09

BlueM