Radarr/src/NzbDrone.Host/CancelHandler.cs

70 lines
1.8 KiB
C#
Raw Normal View History

using System;
using NLog;
using NzbDrone.Core.Lifecycle;
namespace Radarr.Host
{
public interface ICancelHandler
{
void Attach();
}
2019-12-22 21:24:11 +00:00
public class CancelHandler : ICancelHandler
{
2019-12-22 22:08:53 +00:00
private readonly ILifecycleService _lifecycleService;
private object _syncRoot;
private volatile bool _cancelInitiated;
2019-12-22 21:24:11 +00:00
public CancelHandler(ILifecycleService lifecycleService)
{
_lifecycleService = lifecycleService;
}
public void Attach()
{
Console.CancelKeyPress += HandlerCancelKeyPress;
_syncRoot = new object();
}
2019-12-22 21:24:11 +00:00
private void HandlerCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
// Tell system to ignore the Ctrl+C and not terminate. We'll do that.
e.Cancel = true;
2019-12-22 21:24:11 +00:00
var shouldTerminate = false;
lock (_syncRoot)
{
shouldTerminate = _cancelInitiated;
_cancelInitiated = true;
}
2019-12-22 21:24:11 +00:00
// TODO: Probably should schedule these on the threadpool.
if (shouldTerminate)
{
UngracefulShutdown();
}
else
{
GracefulShutdown();
2019-12-22 21:24:11 +00:00
}
}
2019-12-22 21:24:11 +00:00
private void GracefulShutdown()
{
Console.WriteLine("Shutdown requested, press Ctrl+C again to terminate directly.");
2019-12-22 22:08:53 +00:00
// TODO: Sent ApplicationShutdownRequested event or something like it.
_lifecycleService.Shutdown();
}
2019-12-22 21:24:11 +00:00
private void UngracefulShutdown()
{
Console.WriteLine("Termination requested.");
2019-12-22 22:08:53 +00:00
// TODO: Kill it. Shutdown NLog and invoke Environment.Exit.
LogManager.Configuration = null;
Environment.Exit(0);
}
}
}