c# - 强制 TopShelf 服务的单个实例

标签 c# windows-services single-instance topshelf

我正在使用 TopShelf 托管我的 Windows 服务。这是我的设置代码:

static void Main(string[] args)
{
    var host = HostFactory.New(x =>
    {
        x.Service<MyService>(s =>
        {
            s.ConstructUsing(name => new MyService());
            s.WhenStarted(tc => tc.Start());
            s.WhenStopped(tc => tc.Stop());
        });

        x.RunAsLocalSystem();
        x.SetDescription(STR_ServiceDescription);
        x.SetDisplayName(STR_ServiceDisplayName);
        x.SetServiceName(STR_ServiceName);
    });

    host.Run();
}

我需要确保我的应用程序只能同时运行一个实例。目前,您可以将其作为 Windows 服务和任意数量的控制台应用程序同时启动。如果应用程序在启动期间检测到其他实例,它应该退出。

我很喜欢mutex基于方法,但不知道如何使它与 TopShelf 一起工作。

最佳答案

这对我有用。事实证明这真的很简单——互斥代码只存在于控制台应用程序的 Main 方法中。以前我用这种方法进行了假阴性测试,因为我在互斥量名称中没有“全局”前缀。

private static Mutex mutex = new Mutex(true, @"Global\{my-guid-here}");

static void Main(string[] args)
{
    if (mutex.WaitOne(TimeSpan.Zero, true))
    {
        try
        {
            var host = HostFactory.New(x =>
            {
                x.Service<MyService>(s =>
                {
                    s.ConstructUsing(name => new MyService());
                    s.WhenStarted(tc =>
                    {
                        tc.Start();
                    });
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();
                x.SetDescription(STR_ServiceDescription);
                x.SetDisplayName(STR_ServiceDisplayName);
                x.SetServiceName(STR_ServiceName);
            });

            host.Run();
        }
        finally
        {
            mutex.ReleaseMutex();
        }
    }
    else
    {
        // logger.Fatal("Already running MyService application detected! - Application must quit");
    }
}

关于c# - 强制 TopShelf 服务的单个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11487541/

相关文章:

c# - 计算球击中目标所需的初始速度

c# - 没有接口(interface)的 ChannelFactory<T>

c# - 为什么 GetCustomAttributes 返回 object[] 而不是 Attribute[]?

java - 我什么时候应该使用惰性单例而不是普通单例?

Android 将信息传递给 SingleInstance Activity

java - 如何实现单实例Java应用程序?

c# - 使用枚举和继承的工厂设计模式

powershell - 当命令行中带有引号时,如何在Powershell中安装Windows服务?

visual-studio - 在visual studio中添加服务安装程序和服务进程安装程序

windows-7 - 安装Windows服务后重新启动计算机