转移 .NET 互斥锁的所有权
我读过有关互斥锁由线程拥有并且只能由拥有线程使用的信息。在 这个答案解决方案表明,每个进程必须在向另一个进程发出已通过信号之前获得互斥锁的所有权。我必须在这里承认我的愚蠢,我不知道如何使用 IPC 事件,因为它们没有出现在我阅读的 MSDN 中,我喜欢唯一命名的 mutex
作为我的解决方案但我什至不知道如何在 WindowsService 和常规进程之间转移所有权。请帮忙。
我可以补充一下,Jon Skeet 的教程 此处 告诉我,要在不同的用户,正如我认为的 LocalSystem 一样,需要在互斥体名称前加上“Global\”前缀。我在 .NET 文档中找不到任何提及这一点的内容,我认为他是对的,我必须更多地关注 MSDN 系统之外的内容。
I've read about mutex
's being owned by threads and only usable by the owning thread. In this answer the solution suggests that each process must take ownership of the mutex before signalling the other that is is through. I must admit my stupidity here, I don't know how I would use events for IPC as they haven't popped up in my reading of MSDN, I like the uniquely named mutex
's as my solution but I don't even know how to transfer ownership between the WindowsService and regular process. Please help.
Can I add, Jon Skeet's tutorial here informs me that to communicate between different users, as I suppose LocalSystem
to be, requires prefixing mutex
names with 'Global\'. I could not find any mention of this in the .NET documentation, I suppose he is right and must I look outside of the MSDN system more than I do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获得现有互斥锁的所有权,您可以使用静态方法 Mutex.OpenExisting() 和 MutexRights = TakeOwnership
考虑到 OpenExisting() 可能会抛出 UnauthorizedAccessException 异常,我建议使用以下构造函数创建一个新的互斥体:
然后通过分析
createdNew
变量的值,您可以检查互斥体是否已存在或是否创建了新的互斥体。To take ownership on already existing Mutex you can use static method Mutex.OpenExisting() with MutexRights = TakeOwnership
Considering that OpenExisting() can throw UnauthorizedAccessException exception I would suggest to create a new Mutex using following constructor:
and then by analyzing a value of the
createdNew
variable you can check whether mutext already exists or new one was created.第一个过程:
现在是第二个过程的代码。
First process:
Now the code for second process.
此页面似乎相当完整地回答了我的问题,这里尝尝:
This page seems to have answered my question fairly completely, here's a taste: