简体   繁体   中英

Force single instance of TopShelf service

I'm using TopShelf to host my windows service. This is my setup code:

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();
}

I need to ensure that only one instance of my application can be running at the same time. Currently you can start it as windows service and any number of console apps simultaneously. If application detects other instance during startup it should exit.

I really like mutex based approach but have no idea how to make this working with TopShelf.

This is what worked for me. It turned out to be really simple - mutex code exists only in Main method of console app. Previously I had a false negative test with this approach because I had no 'Global' prefix in mutex name.

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");
    }
}

A simpler version:

static void Main(string[] args)
{
    bool isFirstInstance;
    using (new Mutex(false, "MUTEX: YOUR_MUTEX_NAME", out isFirstInstance))
    {
        if (!isFirstInstance)
        {
            Console.WriteLine("Another instance of the program is already running.");
            return;
        }

        var host = HostFactory.New(x =>
        ...
        host.Run();
    }
}

只需将互斥代码添加到tc.Start()并在tc.Stop()中释放Mutex,还将互斥代码添加到控制台应用程序的Main。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM