SoraV2Utils/SoraV2Utils_Agent/ServiceMonitor.cs
krjan02 26cde137c9
Some checks failed
Build and Relase / build-release (push) Failing after 38s
Build and Relase / create-release (push) Failing after 10s
Initial commit (1.0.0)
2025-01-13 16:27:29 +01:00

56 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace SoraV2Utils_Agent
{
public class ServiceMonitor
{
// Event to notify when the service stops
public event EventHandler ServiceStopped;
private Timer _timer;
private string _serviceName;
public ServiceMonitor(string serviceName)
{
_serviceName = serviceName;
// Set up the timer to check service status periodically
_timer = new Timer(1000);
_timer.Elapsed += CheckServiceStatus;
_timer.Start();
}
private void CheckServiceStatus(object sender, ElapsedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController(_serviceName);
// Check the current status of the service
if (serviceController.Status == ServiceControllerStatus.Stopped)
{
// Raise the ServiceStopped event
OnServiceStopped();
_timer.Stop(); // Stop the timer after detecting that the service has stopped
}
}
catch (Exception ex)
{
Console.WriteLine($"Error checking service status: {ex.Message}");
}
}
// Event handler to raise the ServiceStopped event
protected virtual void OnServiceStopped()
{
ServiceStopped?.Invoke(this, EventArgs.Empty);
}
}
}