I have created a c# service which I can run as standalone (console) application from console and also as a windows service. I want to stop run these two (stand alone exe and windows service) to run simultaneously. I want to stop launching this application as a service if i have already started this application from console as a standalone application (or) I want to stop this application starting from console if i have already stated this application as a service. i have tried some of the approaches available (Mutex approach) but they are working only for "stop launching same application twice (2 standalone applications)" but not for "stand alone windows application and windows service".
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MyService.exe", out createdNew))
{
if (createdNew)
{
//new app
MyService service = new MyService();
//Launch as console application
if (Environment.UserInteractive)
{
service.OnStartForConsole();
if (service.IsServiceStartedSuccessfully)
{
//wait for user to quite the application
Console.ReadLine();
}
}
service.OnStopForConsole();
}
else
{
//Launching as windows service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
service
};
ServiceBase.Run(ServicesToRun);
}
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
Console.WriteLine("Already started the proces.");
break;
}
}
}
}
}
can anyone help me how can I achieve this.
thanks in advance.