2

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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

1 Answers1

6

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

sll
  • 61,540
  • 22
  • 104
  • 156