4

我正在使用 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 服务和任意数量的控制台应用程序同时启动。如果应用程序在启动期间检测到其他实例,它应该退出。

我真的很喜欢基于互斥锁的方法,但不知道如何使用 TopShelf。

4

3 回答 3

5

这对我有用。结果非常简单——互斥代码只存在于控制台应用程序的 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");
    }
}
于 2012-08-14T19:17:19.833 回答
1

一个更简单的版本:

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();
    }
}
于 2016-05-13T09:00:20.477 回答
0

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

于 2012-07-14T23:06:13.187 回答