是否可以检查是否可以打开System.Threading.EventWaitHandle而不抛出异常?

时间:2012-03-30 13:02:05

标签: c# .net concurrency ipc event-wait-handle

我有

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

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

如果没有抛出/处理异常,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:5)

.NET 4.5起,对于使用WaitHandleCannotBeOpenedException方法不存在命名系统事件的情况,您可以消除TryOpenExisting()异常:

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

  

如果您不确定是否存在命名同步事件,请使用   此方法重载而不是OpenExisting方法重载,   如果同步事件不存在则抛出异常