gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:54:50 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com