SoraV2Utils/SoraV2Utils_Service/AgentProcessHandler.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

95 lines
2.8 KiB
C#

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace SoraV2Utils_Service
{
internal class AgentProcessHandler
{
private Process _notificationHandlerProcess;
public AgentProcessHandler()
{
RunAgentHandler();
}
private void RunAgentHandler()
{
string notificationHandlerPath = GetNotificationHandlerPath();
if (LaunchProcess(notificationHandlerPath))
{
_notificationHandlerProcess = GetRunningProcess("SoraV2Utils_Agent");
if (_notificationHandlerProcess != null)
{
_notificationHandlerProcess.Exited += OnNotificationHandlerExited;
_notificationHandlerProcess.EnableRaisingEvents = true;
}
}
else
{
Console.WriteLine("Failed to start the notification handler process.");
}
}
private string GetNotificationHandlerPath()
{
return AppDomain.CurrentDomain.BaseDirectory + "\\SoraV2Utils_Agent.exe";
}
private bool LaunchProcess(string path)
{
try
{
ApplicationLauncher.CreateProcessInConsoleSession(path, true);
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Error launching process: {ex.Message}");
return false;
}
}
private Process GetRunningProcess(string processName)
{
return Process.GetProcessesByName(processName).FirstOrDefault();
}
private void OnNotificationHandlerExited(object sender, EventArgs e)
{
Console.WriteLine("Process exited. Restarting...");
RestartNotificationHandler();
}
private void RestartNotificationHandler()
{
Thread.Sleep(1000); // Delay before restarting the process
RunAgentHandler();
}
public void StopNotificationHandler()
{
if (_notificationHandlerProcess != null && !_notificationHandlerProcess.HasExited)
{
_notificationHandlerProcess.Kill();
_notificationHandlerProcess.WaitForExit(); // Ensure the process is fully terminated
Console.WriteLine("Process stopped.");
}
UnsubscribeFromExitEvent();
}
private void UnsubscribeFromExitEvent()
{
if (_notificationHandlerProcess != null)
{
_notificationHandlerProcess.Exited -= OnNotificationHandlerExited;
Console.WriteLine("Event handler unregistered.");
}
}
}
}