SEBWIN-312: Fixed event handling for external application instances.

This commit is contained in:
dbuechel 2019-11-13 11:43:34 +01:00
parent 8dacc208ea
commit 4f930a26d8
2 changed files with 40 additions and 27 deletions

View file

@ -58,11 +58,11 @@ namespace SafeExamBrowser.Applications
if (instances.Any()) if (instances.Any())
{ {
logger.Info("Terminating application..."); logger.Info("Terminating application...");
}
foreach (var instance in instances) foreach (var instance in instances)
{ {
instance.Terminate(); instance.Terminate();
}
} }
} }
} }

View file

@ -50,12 +50,7 @@ namespace SafeExamBrowser.Applications
public void Initialize() public void Initialize()
{ {
process.Terminated += Process_Terminated; InitializeEvents();
timer = new Timer(ONE_SECOND);
timer.Elapsed += Timer_Elapsed;
timer.Start();
logger.Info("Initialized application instance."); logger.Info("Initialized application instance.");
} }
@ -64,37 +59,55 @@ namespace SafeExamBrowser.Applications
const int MAX_ATTEMPTS = 5; const int MAX_ATTEMPTS = 5;
const int TIMEOUT_MS = 500; const int TIMEOUT_MS = 500;
timer.Elapsed -= Timer_Elapsed;
timer?.Stop();
var terminated = process.HasTerminated; var terminated = process.HasTerminated;
for (var attempt = 0; attempt < MAX_ATTEMPTS && !terminated; attempt++) if (!terminated)
{ {
terminated = process.TryClose(TIMEOUT_MS); FinalizeEvents();
}
for (var attempt = 0; attempt < MAX_ATTEMPTS && !terminated; attempt++) for (var attempt = 0; attempt < MAX_ATTEMPTS && !terminated; attempt++)
{ {
terminated = process.TryKill(TIMEOUT_MS); terminated = process.TryClose(TIMEOUT_MS);
} }
if (terminated) for (var attempt = 0; attempt < MAX_ATTEMPTS && !terminated; attempt++)
{ {
logger.Info("Successfully terminated application instance."); terminated = process.TryKill(TIMEOUT_MS);
} }
else
{ if (terminated)
logger.Warn("Failed to terminate application instance!"); {
logger.Info("Successfully terminated application instance.");
}
else
{
logger.Warn("Failed to terminate application instance!");
}
} }
} }
private void Process_Terminated(int exitCode) private void Process_Terminated(int exitCode)
{ {
logger.Info($"Application instance has terminated with exit code {exitCode}."); logger.Info($"Application instance has terminated with exit code {exitCode}.");
FinalizeEvents();
Terminated?.Invoke(Id); Terminated?.Invoke(Id);
} }
private void InitializeEvents()
{
timer = new Timer(ONE_SECOND);
timer.Elapsed += Timer_Elapsed;
timer.Start();
process.Terminated += Process_Terminated;
}
private void FinalizeEvents()
{
timer.Elapsed -= Timer_Elapsed;
timer.Stop();
process.Terminated -= Process_Terminated;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e) private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ {
var success = process.TryGetWindowTitle(out var title); var success = process.TryGetWindowTitle(out var title);