如何在 windows 服务中实现互斥量

How to implement mutex in windows service

你好,我是线程主题的新手,我需要在我的 windows 服务中添加一个 Mutex,因为每当我 运行 它时,它都会在 awesome.exe fantastic.bat 如果关闭则打开。

Fantastic.bat

@echo off
:1
"C:\awesome.exe"
goto :1

我创建了一个 C# 项目来创建 windows 服务,我跟进了 this guide,跟进非常简单,瞧!我按预期获得了 windows 服务,但是我认为互斥锁是一个合适的方法,以避免一遍又一遍地打开大量进程

MyService.cs

using System;
using System.ServiceProcess;
using System.Timers;

namespace Good_enough_service
{
    public partial class GoodService : ServiceBase
    {
        private Timer _syncTimer = null;
        public GoodService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _syncTimer = new Timer();
            this._syncTimer.Interval = 1000;
            this._syncTimer.Elapsed +=
              new System.Timers.
                ElapsedEventHandler(this.syncTimerTicker);

            _syncTimer.Enabled = true;
        }

        protected override void OnStop()
        {

            _syncTimer.Enabled = false;
        }

        private void syncTimerTicker(object sender, EventArgs e)
        {

            System.Diagnostics.Process.Start(@"C:\fantastic.bat");
        }
    }
}

我能够安装该服务,但它弹出了很多次蝙蝠,因此它打开了很多次我的 awesome.exe

我正在查看很多关于如何在 Whosebug、Microsoft 文档和 google 查询中使用 Mutex 的示例,但是老实说,因为我对这个主题还很陌生,所以我'我对如何构建它感到困惑,有人可以帮助我实现它吗?

Program.cs这是服务项目的一部分

using System.ServiceProcess;

namespace Good_enough_service
{
    static class Program
    {
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new GoodService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

鉴于您的目标只是启动一个 .exe 并确保它保持 运行,您需要做的就是使用 Process 对象直接启动可执行文件,并且然后通过 HasExited 属性 监视它是否完成。当进程退出时,只需启动一个新进程(或重新启动现有进程)。

Process.HasExited 属性