Search code examples
c#multithreadingwaithandle

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?


Solution

  • 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.