Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can ManualResetEvent.Set() return false?

According the the MSDN documentation, Set() and Reset() on ManualResetEvent (or any EventWaitHandle) returns a boolean indicator whether or not the operation was successful.

Under which circumstances can this call return false, and what am I supposed to do if it does?

like image 841
SoftMemes Avatar asked Nov 03 '10 23:11

SoftMemes


People also ask

How ManualResetEvent works?

When the controlling thread completes the activity, it calls ManualResetEvent. Set to signal that the waiting threads can proceed. All waiting threads are released. Once it has been signaled, ManualResetEvent remains signaled until it is manually reset by calling the Reset() method.

When to use ManualResetEvent?

ManualResetEvent is used for send signals between two or more threads. Multiple threads can enter into a waiting/blocking state by calling the WaitOne method on ManualResetEvent object. When controlling thread calls the Set method all the waiting threads are unblocked and free to proceed.

What is ManualResetEvent and AutoResetEvent in C#?

The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.

Is ManualResetEvent thread safe?

ManualResetEvent is thread safe. All its instance members are thread safe, therefore you do not have perform any thread synchronization.


1 Answers

I wasn't sure how to answer this and looking at a lot of MSDN examples the Set return value is ignored so it must not be important or likely to happen.

But that wasn't good enough. I fired up my VM and I opened up Reflector to take a look at the code. ManualResetEvent doesn't have Set but it inherits from EventWaitHandle which does. Here's the code:

public bool Set()
{
    bool flag = Win32Native.SetEvent(base.safeWaitHandle);
    if (!flag)
    {
        __Error.WinIOError();
    }
    return flag;
}

Where SetEvent is imported from Kernel32:

[DllImport("kernel32.dll", SetLastError=true)]
internal static extern bool SetEvent(SafeWaitHandle handle);

The WinIOError() call just calls GetLastWin32Error which we don't really care about. Basically this means for the call to return false, something pretty wrong would have had to have occurred in the Win32 native code.

Putting this info together with the fact that code hosted in official MSDN documentation ignores the return value (why not? what are you going to do if the kernel fails anyway?) you can safely ignore it yourself if you want to clean your logic up a bit or get it and log it if you're especially pedantic.

like image 137
Erik Noren Avatar answered Oct 18 '22 13:10

Erik Noren