【发布时间】:2020-05-29 10:53:52
【问题描述】:
您好,我是线程主题的新手,我需要在我的 Windows 服务中添加一个 Mutex,因为每当我运行它时,它会一遍又一遍地弹出 awesome.exe,如果它关闭了则打开一个梦幻般的.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
我正在查看很多关于如何在我发现的 stackoverflow、微软文档和谷歌查询中使用互斥锁的示例,但是老实说,因为我对这个主题很陌生,所以我有点困惑如何要建立这个,有人可以帮助我如何实现这个吗?
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?互斥锁是一种用于协调多个线程而不是多个进程的工具。
-
抱歉,我的回复延迟了,我正在寻找一种方法来运行我的服务,该服务将运行我的 Fantastic.bat 所以它会在我关闭时打开我的 awesome.exe。就这么简单,但是我面临的问题是我是这个主题的菜鸟,我只是遵循了关于如何创建 Windows 服务的指南,这是我在帖子中发布的代码,tbh 我没有了解要在代码中剪切哪些部分以避免一遍又一遍地打开 Fantastic.bat 我知道如果我将计时器增加到 1 小时,它将再次打开蝙蝠但进程会重复 X_X
标签: c# windows multithreading service mutex