简体   繁体   English

创建跨进程EventWaitHandle

[英]Creating a Cross-Process EventWaitHandle

I have two windows application, one is a windows service which create EventWaitHandle and wait for it. 我有两个Windows应用程序,一个是Windows服务,它创建EventWaitHandle并等待它。 Second application is a windows gui which open it by calling EventWaitHandle.OpenExisting() and try to Set the event. 第二个应用程序是一个windows gui,它通过调用EventWaitHandle.OpenExisting()打开它并尝试设置事件。 But I am getting an exception in OpenExisting. 但我在OpenExisting中遇到异常。 The Exception is "Access to the path is denied". 例外是“拒绝访问路径”。

windows Service code windows服务代码

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

Windows GUI code Windows GUI代码

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. 我用两个示例控制台应用程序尝试了相同的代码,它工作正常。

You need to use the version of the EventWaitHandle constructor that takes an EventWaitHandleSecurity instance. 您需要使用带有EventWaitHandleSecurity实例的EventWaitHandle构造函数的版本。 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);
...

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\\"). 此外,如果您在Vista或更高版本上运行,则需要在全局命名空间中创建事件(即,在名称前加上“Global \\”)。 You'd also have to do this on Windows XP if you use the "Fast User Switching" feature. 如果使用“快速用户切换”功能,则还必须在Windows XP上执行此操作。

This might be caused by the service process running at an elevated privilege level, but the GUI process is not. 这可能是由服务进程在提升的权限级别运行引起的,但GUI进程则不是。 If you put the same code into two console apps, they'll both be running at user level and won't have any trouble accessing each other's named shared objects. 如果将相同的代码放入两个控制台应用程序中,它们都将在用户级别运行,并且在访问彼此的命名共享对象时不会遇到任何问题。

Try running the GUI app with the "Run as administrator" flag from the Windows start menu. 尝试使用Windows开始菜单中的“以管理员身份运行”标志运行GUI应用程序。 If that solves the issue, you need to read up on how to request elevation within your code. 如果这样可以解决问题,那么您需要了解如何在代码中请求提升。 (I haven't done that) (我还没有这样做)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM