我正在使用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中工作。
发布于 2012-08-15 03:17:20
这就是对我有效的方法。它被证明是非常简单的-互斥代码只存在于控制台应用的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");
}
}发布于 2016-05-13 17:00:20
更简单的版本:
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();
}
}发布于 2012-07-15 07:06:13
只需将互斥锁代码添加到tc.Start()中并在tc.Stop()中释放互斥锁,然后将互斥锁代码添加到控制台应用程序的Main中。
https://stackoverflow.com/questions/11487541
复制相似问题