C
C#12mo 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();
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();
}
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;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
Console.CancelKeyPress += _serverHandler.CtrlCPressed;
return Task.CompletedTask;
}
1 Reply
revolt
revoltOP12mo ago
Adding more to main cause of message limit. My goal is to simply interrupt the default behaviour of ctrl+c and stop the spawned child manually without stopping the main process
Want results from more Discord servers?
Add your server