您好,我是线程主题的新手,我需要在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/