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

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

문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top