C#C
C#2y ago
revolt

CancelKeyPress not being handled/interrupted correctly

The issue is that on ctrl+c press the application does call CancelKeyPress event, however I'm assuming it is not respecting e.Cancel = true correctly. Either that or the main program passes ctrl+c to the spawned process and does not respect e.Cancel = true.

Code :
Program.cs
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
            IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile("settings.json", optional: true, reloadOnChange: true).Build();

            builder.Services.Configure<SettingsConfig>(configuration.GetSection("Settings"));
            builder.Services.AddSingleton<ServerHandler>();
            builder.Services.AddSingleton<IHostLifetime, CustomLifetime>();
            using IHost host = builder.Build();
            ServerHandler _serverHandler = host.Services.GetRequiredService<ServerHandler>();
            _serverHandler.Create();
            host.Run();

ServerHandler.cs (Relevant code. _serverProcess is a reference to new spawned Process, not the current main process)
public void CtrlCPressed(object? sender, ConsoleCancelEventArgs e)
        {
            if (!shouldExitNext)
            {
                e.Cancel = true;
                shouldExitNext = true;
                Console.WriteLine("Ctrl+C pressed. Running a method...");
                StopServerProcess();
                
            }
            else
            {
                Console.WriteLine("Ctrl+C pressed again. Exiting...");
                e.Cancel = false;

            }
        }

        public void StopServerProcess()
        {
            SendServerMessage("stop");
            _serverProcess.WaitForExit();
        }

CustomLifetime.cs
 public Task WaitForStartAsync(CancellationToken cancellationToken)
        {
            Console.CancelKeyPress += _serverHandler.CtrlCPressed;
            return Task.CompletedTask;
        }
Was this page helpful?