c# - 如何在Windows Service中实现互斥

标签 c# windows multithreading service mutex

您好,我是线程主题的新手,我需要在Windows服务中添加一个Mutex,因为每当我运行Mutex时,它都会在awesome.exe之上弹出,如果关闭的话,它将打开great.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");
        }
    }
}

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

我正在看很多关于如何在我发现的stackoverflow,Microsoft docs和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 Property

关于c# - 如何在Windows Service中实现互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60212789/

相关文章:

java.lang.RuntimeException : No OpenGL context found in the current thread while generating world in thread

c# - 如何使用 C# 渲染 pdf

c# - Entity Framework 与相同实体类型但具有不同关系类型的多对多关系

C#:按可为空的 DateTime 属性对对象列表进行排序

c++ - 如何使用 Cygwin 构建 Google RE2?

windows - 唯一标识 Linux/Windows 上的用户 session

c# - 获取句柄并写入启动我们进程的控制台

c# - Dictionary<TKey, TSource> 的神秘行为

java - JavaFX Platform.runLater 的使用和从不同线程访问 UI

c# - Parallel.ForEach<T> 的某些项目在 ThreadPool 上运行,有些则不