My C# application creates a batch script and then spawns a Process to execute this script.
This application needs to run as a Windows service. Additionally I also need a standalone mode where I will indicate via a command line parameter that this should just run once and exit.
The problem is that when I run the standalone version, I can see multiple instances of the app (Launcher) getting spawned. But if I were to run it from within Visual Studio, it behaves i.e executes once and exits.
Can someone help me understand whats going on?
Here’s the class with the main()
static class Launcher
{
static void Main(String[] args)
{
if(args[0] == "/standalone")
{
using(MyService service = new MyService())
{
service.StartService();
service.StopService();
}
}
else
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new MyService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
}
The MyService class:
public partial class MyService : ServiceBase
{
protected override void OnStart(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "C:\abc.bat";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
}
protected override void OnStop()
{
// Log something
}
public void StartService()
{ this.OnStart(null); }
public void StopService()
{ this.OnStop() }
}
if there are multiple instances, then process.start was called more then once. I would recommend that you write out logs and trace why your process.start is being called multiple times