Hi,
I am trying to stop a service, change the associated applications config file, start the service again, perform a task, and then reverse the process.
The problem I believe I am having is that the service itself, sometimes, can take a while to stop (other times it's lightning-fast).
The issue seems to arise when I try and reverse the config file change (the file config part is fine, it's the Stop/start of the server that seems to take longer than excepted ).
I was wondering if someone could advise me on the best way to stop and wait fully for a service to terminate before I can then continue.
So far, I have
ServiceController appDriver = new ServiceController("ServiceName");
private void Form1_Load(object sender, EventArgs eg)
{
try
{
string Status =appDriver.Status.ToString();
if (appStatus == "Running")
{
appDriver.Stop();
appDriver.WaitForStatus(ServiceControllerStatus.Stopped);
while (appStatus != "Stopped")
{
appDriver.Refresh();
appStatus = OLDDriver.Status.ToString();
}
}
< make a change to config file >
appStatus = appDriver.Status.ToString();
if (appStatus == "Stopped")
{
appDriver.Start();
while (appStatus != "Running")
{
appDriver.Refresh();
appStatus = appDriver.Status.ToString();
}
}
< above code snippet works fine >
< do some more things while the application is using the new config file >
/// tried this as the previous coded hung app as the service took too long to stop, but getting same issue again
Process cmdlne = new Process();
cmdlne.StartInfo.FileName = "cmd.exe";
cmdlne.StartInfo.CreateNoWindow = true;
cmdlne.StartInfo.RedirectStandardInput = true;
cmdlne.StartInfo.RedirectStandardOutput = true;
cmdlne.StartInfo.UseShellExecute = false;
cmdlne.Start();
cmdlne.StandardInput.WriteLine("net stop ServiceName");
cmdlne.StandardInput.Flush();
cmdlne.StandardInput.Close();
cmdlne.WaitForExit();
< revert change to config file >
appDStatus = appDriver.Status.ToString();
if (appStatus == "Stopped")
{
appDriver.Start();
while (appStatus != "Running")
{
appDriver.Refresh();
appStatus = appDriver.Status.ToString();
}
}
< carry on with other code >
}
The service can take up to 60 seconds to terminate, and although I think my code should be waiting nicely for this to happen, it doesn't seem to be.
Thank you