Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Windows服务-一次只允许一个实例_C#_Windows_Service - Fatal编程技术网

C# Windows服务-一次只允许一个实例

C# Windows服务-一次只允许一个实例,c#,windows,service,C#,Windows,Service,我尝试使用下面的代码来限制windows服务的第二个实例,但下面的代码对我不起作用,有人能帮我吗。 我已经设置了运行服务的时间间隔,即5分钟,若第一个实例启动并运行,在5分钟后,第二个实例启动,即使第一个实例并没有完成 static class Program { [STAThread] static void Main() { bool ok; System.Threading.Mutex m = new System.Threading.Mute

我尝试使用下面的代码来限制windows服务的第二个实例,但下面的代码对我不起作用,有人能帮我吗。
我已经设置了运行服务的时间间隔,即5分钟,若第一个实例启动并运行,在5分钟后,第二个实例启动,即使第一个实例并没有完成

static class Program
{
    [STAThread]
    static void Main()
    {

     bool ok;
     System.Threading.Mutex m = new System.Threading.Mutex(true, "ImageImportService", out ok);
        if (!ok)
        {
            return;
        }
        GC.KeepAlive(m);
        if (PriorProcess() != null)
        {
            return;
        }
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
            { 
                new ImageImportService() 
            };
        ServiceBase.Run(ServicesToRun);
    }
    public static Process PriorProcess()
    {
        Process curr = Process.GetCurrentProcess();
        Process[] procs = Process.GetProcessesByName(curr.ProcessName);
        foreach (Process p in procs)
        {
            if ((p.Id != curr.Id) && (p.MainModule.FileName == curr.MainModule.FileName))
                return p;
        }
        return null;
    }
}

服务控制管理器是Windows的一个组件,如果Windows服务已在运行,则不允许启动该服务。就靠它吧

您需要做的主要事情是永远不要直接启动可执行文件。相反,当从代码启动服务时,请使用
ServiceController
类,当手动启动/停止服务时,请使用控制面板(
services.msc


在某些情况下,您可能需要采取额外的步骤,以确保服务停止后不会保留任何资源,从而阻止其自己的后续启动,直到某个较低级别的超时。但您的问题中没有任何内容表明您已经遇到了此类问题(例如,重新绑定TCP端口)。

是否可能运行同一服务的两个实例?它是如何工作的?到底什么是失败的?我已经设置了运行服务的时间间隔,即5分钟,如果第一个实例启动并运行,则第二个实例通常会启动5分钟,即使第一个实例未完成。您调用
GC.KeepAlive(m)
太早了。您的互斥对象可能会被垃圾收集并最终确定,在调用后立即释放互斥对象。我需要调用GC.KeepAlive(m)方法。