Is it possible to check whether System.Threading.EventWaitHandle can be opened without throwing exceptions?

StackOverflow https://stackoverflow.com/questions/9943522

Question

I have

try
{
    using (var eventWaitHandle = EventWaitHandle.OpenExisting(name))
    {
        eventWaitHandle.Set();
    }

    Environment.Exit(0);
}
catch(WaitHandleCannotBeOpenedException)
{
    // register new handle code goes here
}

Is there any way to do that without throwing/handling exceptions?

Was it helpful?

Solution

Since .NET 4.5 you can eliminate WaitHandleCannotBeOpenedException exception for case when named system event does not exist by using TryOpenExisting() method:

EventWaitHandle result = null;
if (!EventWaitHandle.TryOpenExisting("eventName", out result))
{
   if (result == null)
   {
      // event was not found
   }else
   {
      // result represent a cross process WaitEvent handle
   }
}

public static bool TryOpenExisting(
                      string name,
                      out EventWaitHandle result
)

MSDN:

If you are uncertain whether a named synchronization event exists, use this method overload instead of the OpenExisting method overload, which throws an exception if the synchronization event does not exist

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top