是否可以检查System.Threading.EventWaitHandle是否可以在不抛出异常的情况下打开?

问题描述:

是否可以检查System.Threading.EventWaitHandle是否可以在不抛出异常的情况下打开?

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

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

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

+0

我没有找到它 – 2012-03-30 13:10:26

由于.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方法过载, 如果同步事件不存在则抛出异常