我有
try
{
using (var eventWaitHandle = EventWaitHandle.OpenExisting(name))
{
eventWaitHandle.Set();
}
Environment.Exit(0);
}
catch(WaitHandleCannotBeOpenedException)
{
// register new handle code goes here
}
如果没有抛出/处理异常,有没有办法做到这一点?
答案 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方法重载, 如果同步事件不存在则抛出异常