gpt4 book ai didi

c# - Windows 服务看不到命名信号量

转载 作者:太空狗 更新时间:2023-10-29 20:17:51 27 4
gpt4 key购买 nike

我正在尝试调解一个小型 Windows 服务,使其在启动期间等待来自另一个进程的信号。可以肯定的是,我知道这种方法有时可能(甚至会)导致服务启动超时。事实并非如此。

问题出在我用于调解目的的命名 System.Thread.Sempaphore 上。使用以下构造在其他地方创建和获取信号量。 GC 没有任何变化,因为出于测试目的,我明确地在给定行下方中断了执行。

Boolean newOne;
System.Threading.Semaphore rootSemaphore =
new System.Threading.Semaphore(1, 1, "DummyServiceSemaphore", out newOne);

显然,上面的代码运行良好。以下代码在 Debug模式或控制台应用程序下执行时运行良好:

Boolean createdNew;
System.Threading.Semaphore semaphore =
new System.Threading.Semaphore(1, 1, "DummyServiceSemaphore", out createdNew);
if (createdNew)
throw new Exception("That's not what we wanted");

当作为 Windows 服务的一部分执行时,完全相同的代码会失败:

static class Program
{
static void Main(string[] args)
{
Boolean createdNew;
System.Threading.Semaphore semaphore =
new System.Threading.Semaphore(1, 1, "DummyServiceSemaphore", out createdNew);
if (createdNew)
throw new Exception("That's not what we wanted");

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Dummy() };
ServiceBase.Run(ServicesToRun);
}
}

为什么会失败?

我一直在尝试改用 Mutex,但是它还有另一个问题 - 当所有者调用 Mutex.ReleaseMutex() 时等待的应用程序没有 catch ;


更新:

根据 Anurag Ranjhan 的回复,我编辑了信号量创建程序如下,现在一切正常:

Boolean newOne = false;

System.Security.Principal.SecurityIdentifier sid =
new System.Security.Principal.SecurityIdentifier(
System.Security.Principal.WellKnownSidType.WorldSid,
null);

System.Security.AccessControl.SemaphoreSecurity sec =
new System.Security.AccessControl.SemaphoreSecurity();
sec.AddAccessRule(new System.Security.AccessControl.SemaphoreAccessRule(
sid,
System.Security.AccessControl.SemaphoreRights.FullControl,
System.Security.AccessControl.AccessControlType.Allow));

System.Threading.Semaphore rootSemaphore =
new Semaphore(1, 1, "Global\\DummyServiceSemaphore", out newOne, sec);

最佳答案

尝试与 Global\ 一起使用前缀

System.Threading.Semaphore rootSemaphore = 
new System.Threading.Semaphore(1, 1, @"Global\DummyServiceSemaphore", out newOne);

来自comment section of MSDN

If you're using a named Semaphore in Windows, the name you choose isgoverned by Kernel naming guidelines. Some of those guidelines alsoinclude the Kernel Object Namespaces1, which describes the contextof the kernel object. By default, with Terminal Services installed,kernel objects like events are limited to the current Session. This isdone so multiple sessions running in Terminal Services won't adverselyaffect one another. Kernel Object Namespaces describe using "Local","Global" and "Session" prefixes to create kernel objects that canapply to specific namespaces and to communicate with or limitcommunication to processes of a specific scope.

关于c# - Windows 服务看不到命名信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com