创建跨进程EventWaitHandle

Nav*_*eth 19 c# events synchronization process

我有两个Windows应用程序,一个是Windows服务,它创建EventWaitHandle并等待它.第二个应用程序是一个windows gui,它通过调用EventWaitHandle.OpenExisting()打开它并尝试设置事件.但我在OpenExisting中遇到异常.例外是"拒绝访问路径".

windows服务代码

EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName");
wh.WaitOne();
Run Code Online (Sandbox Code Playgroud)

Windows GUI代码

try
{
    EventWaitHandle wh = EventWaitHandle.OpenExisting("MyEventName");
    wh.Set();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

我用两个示例控制台应用程序尝试了相同的代码,它工作正常.

Dea*_*ing 33

您需要使用带有EventWaitHandleSecurity实例的EventWaitHandle构造函数的版本.例如,以下代码应该可以工作(它没有经过测试,但希望能让你入门):

// create a rule that allows anybody in the "Users" group to synchronise with us
var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                          AccessControlType.Allow);
var security = new EventWaitHandleSecurity();
security.AddAccessRule(rule);

bool created;
var wh = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName", out created, security);
...
Run Code Online (Sandbox Code Playgroud)

此外,如果您在Vista或更高版本上运行,则需要在全局命名空间中创建事件(即,在名称前加上"Global \").如果使用"快速用户切换"功能,则还必须在Windows XP上执行此操作.