**Ich installiere diesen Dienst auf Windows Server 2019 (ich dachte nur, ich würde ihn erwähnen
Ich habe einen Windows-Dienst, der sich nach einer bestimmten Zeit mit einer Methode namens ServiceRestartTimer neu starten soll.
Das Problem, das ich habe m gegenübersteht:
Wenn der Dienst den Stop-Status erreicht, scheint er vollständig angehalten zu werden und der Rest des Codes wird nicht mehr ausgeführt.
*Basierend auf den Protokollen, die ich Nachdem ich hinzugefügt habe, ist mir klar geworden, dass genau das passiert.
Das ist mein Code:
Code: Select all
if (AppConfiguration.RestartTimeMin != 0)
{
RestartTimeer.Elapsed += ServiceRestartTimer;
RestartTimeer.Start();
}
Code: Select all
private void ServiceRestartTimer(object sender, ElapsedEventArgs e)
{
try
{
DateTime now = DateTime.Now;
TimeSpan diff = now - LatestReadTime;
Log.WriteToFile("Service Entered ServiceRestartTimer at: " + now.ToString());
// Checking if the delay exceeds the allowed time
if (diff.TotalSeconds > RestartTimeInSec)
{
Ping myPing = new Ping();
// Executing Ping asynchronously
myPing.PingCompleted += (pingSender, pingEventArgs) =>
{
try
{
PingReply reply = pingEventArgs.Reply;
if (reply.Status == IPStatus.Success)
{
Log.WriteToFile("ReStart Service Is Called: " + " In Time : " + DateTime.Now.ToString());
try
{
// Using ServiceController to control the service
ServiceController sc = new ServiceController("MyService");
// Checking the service status before stopping
if (sc.Status == ServiceControllerStatus.Running)
{
Log.WriteToFile($"Service MyService is currently running. Attempting to stop it.");
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15)); // Wait for the service to stop
Log.WriteToFile($"Service MyService stopped successfully.");
}
// Restarting the service after stopping
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(15)); // Wait for the service to start
Log.WriteToFile($"Service MyService started successfully.");
}
catch (Exception ex)
{
Log.WriteToFile($"Error restarting service: {ex.Message}");
}
}
else
{
Log.WriteToFile("Ping failed. Service restart skipped.");
}
}
catch (Exception ex)
{
Log.WriteToFile("Exception in PingCompleted handler: " + ex.Message);
}
};
// Sending Ping asynchronously
myPing.SendAsync(AppConfiguration.IP, 1000, null);
}
}
catch (Exception ex)
{
Log.WriteToFile("Exception in ServiceRestartTimer: " + ex.Message);
}
}
Dieses Protokoll:
Code: Select all
Log.WriteToFile("ReStart Service Is Called: " + " In Time : " + DateTime.Now.ToString());
Code: Select all
Log.WriteToFile($"Service MyService is currently running. Attempting to stop it.");
Code: Select all
Log.WriteToFile($"Service MyService stopped successfully.");
Hilfe erforderlich !
Ich gehe davon aus, dass diese Methode, wenn sie erreicht ist, den Vorgang zum Neustart des Dienstes korrekt ausführen sollte.
Ich habe verschiedene Implementierungen getestet, aber keine von ihnen funktionierten.