我有一个服务,它创建一个带有循环的线程,该循环应该一直运行,直到互斥被另一个进程通知为止。我的服务代码中包含以下内容
private readonly Mutex _applicationRunning = new Mutex(false, @"Global\HsteMaintenanceRunning");
protected override void OnStart(string[] args)
{
new Thread(x => StartRunningThread()).Start();
}
internal void StartRunningThread()
{
while (_applicationRunning.WaitOne(1000))
{
FileTidyUp.DeleteExpiredFile();
_applicationRunning.ReleaseMutex();
Thread.Sleep(1000);
}
}
现在我有了一个控制台应用程序,它应该声明互斥锁并强制退出while循环
var applicationRunning = Mutex.OpenExisting(@"Global\HsteMaintenanceRunning");
if (applicationRunning.WaitOne(15000))
{
Console.Write("Stopping");
applicationRunning.ReleaseMutex();
Thread.Sleep(10000);
}
当控制台应用程序尝试打开互斥锁时,我得到错误消息"The wait completed an an completed mutex“。这是怎么回事?
发布于 2013-04-29 23:50:49
我建议您使用服务的内置停止信号,而不是互斥锁。mutex类更适合于管理对共享资源的独占访问,而这里不是这样做的。您也可以使用系统事件,但是既然服务已经有了一个内置的机制来在它们停止时发出信号,为什么不使用它呢?
您的服务代码将如下所示:
bool _stopping = false;
Thread _backgroundThread;
protected override void OnStart(string[] args)
{
_backgroundThread = new Thread(x => StartRunningThread());
_backgroundThread.Start();
}
protected override void OnStop()
{
_stopping = true;
_backgroundThread.Join(); // wait for background thread to exit
}
internal void StartRunningThread()
{
while (!stopping)
{
FileTidyUp.DeleteExpiredFile();
Thread.Sleep(1000);
}
}
然后,您的控制台应用程序将需要使用框架的ServiceController类将关闭消息发送到您的服务:
using System.ServiceProcess;
...
using (var controller = new ServiceController("myservicename")) {
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15.0));
}
https://stackoverflow.com/questions/16280625
复制相似问题