56 lines
1.6 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|