We're running a C# console program as a scheduled task on Windows. This program itself runs a lot of "tasks" that would need to be gracefully shutdown when the program itself is ended.
Is there a way to run cleanup code (that could take a second or two) when the scheduled task is ended? For instance when it is ended by calling Stop-ScheduledTask from a PowerShell script.
I've tried catching CTRL-C events as well as catching the ProcessExit event of AppDomain, but none of these appear to be called when the scheduled task is ended.
As outlined by rrirower in the comments, another option would be to send a signal to the process before asking it to terminate, but this does not seem better supported on Windows.