0

I want to start 2 related applications. First, I want to start my "Service" application and then my "Client" application. It does not consistently work. Sometimes the client starts up too fast and ends up not being connected to the service. Can someone show me where I need to change my code to work correctly and have the client only start after the service has completely started?

public class Program
{
public static void Main(string[] args)
{
    Console.WriteLine("Starting Service");
    StartService();

    if (IsServiceRunning())
    {
        Console.WriteLine("Starting Client");
        StartClient();
    }

    Console.ReadLine();
}

private static void StartClient()
{
    ProcessStartInfo startInfo = new ProcessStartInfo()
    {
        WorkingDirectory = @"C:\Client",
        FileName = "Client.exe"
    };

    Process.Start(startInfo);
}

private static bool IsServiceRunning()
{
    Console.WriteLine("Check to see is running...");
    Process[] pname = Process.GetProcessesByName("MyCommonService");
    int runningCheck = 0;

    if (pname.Length == 0 || runningCheck < 10)
    {
        Console.WriteLine("Did not find the process. Check again...");
        runningCheck += 1;
        Thread.Sleep(250);
        IsServiceRunning();
    }

    Thread.Sleep(1000);
    return true;
}

private static void StartService()
{
    Console.WriteLine("Starting Service");
    ProcessStartInfo startInfo = new ProcessStartInfo()
    {
        WorkingDirectory = @"C:\Service",
        FileName = "MyCommonService.exe"
    };

    Process.Start(startInfo);
}

}

Wannabe
  • 596
  • 1
  • 8
  • 22

1 Answers1

1

Looks like that'll always depend on how long it takes for the service to "completely start". If the service needs to do network operations to "completely start", you might have no guarantee of when the service has "completely started". Instead of simply waiting what it looks like 3,500 milliseconds, you can use interprocess communication.

What is the simplest method of inter-process communication between 2 C# processes?

Basic idea is to get your service process to communicate back to your program, and if it gives back a string that shows the service has started, only then start your client process.

miara
  • 847
  • 1
  • 6
  • 12