Force TopShelf Service Instance

I use TopShelf to host my Windows service. This is my installation 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 make sure that only one instance of my application can work at a time. Currently, you can run it as a Windows service and any number of console applications at the same time. If the application detects another instance during startup, it should exit.

I really like mutex , but don't know how to get this to work with TopShelf.

+4
source share
3 answers

This is what worked for me. It turned out to be very simple - the mutex code exists only in the main method of the console application. I used to have a false negative test with this approach, because I did not have the "Global" prefix in the 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"); } } 
+5
source

Simple 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(); } } 
+1
source

Just add the mutex code to tc.Start () and release Mutex to tc.Stop (), also add the mutex code to the main console application.

0
source

All Articles