95 lines
2.8 KiB
C#
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.");
|
|
}
|
|
}
|
|
}
|
|
}
|