简体   繁体   中英

How to detect when a console application stopped by a scheduled task in C#?

I have a console application that runs for a specified period of time. In case of the application runs out of the specified time then there a scheduled job that stops the application.

Could you please me know if there is any way to detect when the application stopped by the scheduler?

I have already tried a couple of things eg catch the event on CurrentDomain.ProcessExit and implementing the SetConsoleCtrlHandler but none of them worked.

Thanks, in advance for the suggestions.

If the process is being killed, you can't detect that in the process. You'll need a different solution. Options include having a separate "watcher" process, but my guess it that would be unnecessarily complex here.

I would probably put a canary thread in the process itself that uses a timer and cancellation token to signal the task it should cleanly abort.

The same console app could detect if an instance of itself is already running (eg hung) on start-up and manage a process-kill itself. That way all the logic is in one place, and you don't need the scheduled task to do anything fancy.

Found this article. https://devblogs.microsoft.com/oldnewthing/20040722-00/?p=38373 that explains that killing process can't be handled by application. You have to exit your consoleapp in a nice way rather just killing its process

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM