I would like to pass all the control of the program to the event handler (ConsoleCancelEventHandler). However, once I terminate the overall program by CTRL-C while Globals.object1.runprocess() is executing, the flow goes to the event handler as expected, but the main process continues, disposing of object1, before the handler can retrieve information from object1. The try catch block in the handler work correctly in checking on the object1.Status because the exception thrown until the status is available can be seen.. This code only works correctly if I run in in debug mode, or if I add a delay right after Globals.object1.runprocess() and I terminate the program within that delay. How do I ensure the flow continues ONLY on the process inside the handler and not in main?
using System;
using ownlibraryfoo;
public static class Globals
{
public static foo_type object1;
}
class sample_cs
{
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
try {
Globals.object1.initialize();
Globals.object1.runprocess();
Globals.object1.Dispose();
} catch (fooException e) {
Console.WriteLine("Error code SSSSSSSSSSSSSSSS: " + e.ErrorCode + ". " + e.Message);
}
return;
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Program Terminated Manually");
e.Cancel = true;
Globals.object1.Terminate();
bool tryAgain = true;
/* query solve status until available and handle exception when not available */
while(tryAgain)
{
try
{
if (Globals.object1.Status == FOOINTERRUPTEDSTATUS)
{
Console.WriteLine(" OBJECTIVE = " + Globals.object1.internalattribute);
}
tryAgain = false;
}
catch (FooException f)
{
/* the error output is optional */
Console.WriteLine("Object1 Error code = " + f.ErrorCode);
Console.WriteLine(f.Message);
}
}
Environment.Exit(0);
}
}
question from:
https://stackoverflow.com/questions/66066622/c-why-does-main-process-continues-after-external-event-is-caught-by-signal-han 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…