本文介绍了创建一个跨进程的 EventWaitHandle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two windows application, one is a windows service which create EventWaitHandle and wait for it. Second application is a windows gui which open it by calling EventWaitHandle.OpenExisting() and try to Set the event. But I am getting an exception in OpenExisting. The Exception is "Access to the path is denied".

windows 服务代码

windows Service code

EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName");
wh.WaitOne();

Windows GUI 代码

Windows GUI code

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

我用两个示例控制台应用程序尝试了相同的代码,效果很好.

I tried the same code with two sample console application, it was working fine.

推荐答案

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

You need to use the version of the EventWaitHandle constructor that takes an EventWaitHandleSecurity instance. For example, the following code should work (it's not tested, but hopefully will get you started):

// 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);
...

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

Also, if you're running on Vista or later, you need to create the event in the global namespace (that is, prefix the name with "Global"). You'd also have to do this on Windows XP if you use the "Fast User Switching" feature.

这篇关于创建一个跨进程的 EventWaitHandle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 10:54
查看更多