![](/img/trans.png)
[英]How to pass HostControl instance to custom host service in TopShelf?
[英]Force single instance of TopShelf service
我正在使用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一起使用。
这对我有用。 事实证明这非常简单-互斥代码仅存在于控制台应用程序的Main方法中。 以前,我对此方法进行过否定测试,因为互斥体名称中没有'Global'前缀。
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");
}
}
一个简单的版本:
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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.