开发者

Handling a forced exit

开发者 https://www.devze.com 2023-01-06 04:21 出处:网络
Is there any good way to handle a forced exit in C#? I have a formless C# applicati开发者_如何学编程on that talks to an LCD over serial. Once the application is running, the only way to kill it is wi

Is there any good way to handle a forced exit in C#?

I have a formless C# applicati开发者_如何学编程on that talks to an LCD over serial. Once the application is running, the only way to kill it is with task manager. The trouble with this is that the program needs to turn the LCD off when it is done, and it doesn't look as if my Application.ApplicationExit event is ever fired in this condition.

Any ideas?


Once the application is running, the only way to kill it is with task manager.

My big idea would be to change this.

Stick an icon in the notification area that the user can use to shut your app down properly, or set it up so that running the app again will instead shut down an already-running instance if one exists, or any other way that sounds like a good idea.

Requiring a user to use Task Manager to shut down your application screams poor design.


Write a code in your program loop (with a timer perhaps) to read a file or a registry key. For example if a file at C:\YOURPROGRAM\CLOSEME contains text "closeme", close your program gracefully. Write another program that write that C:\YOURPROGRAM\CLOSEME file. So, whenever you want to shutdown your program, don't use taskmanager, instead, open second program.


Some options:

  • Write a separate process with a GUI that can start and stop the main process. For example, when you install the Apache web server on Windows the server itself is installed as a service. It can be started and stopped from the system services management panel, but it also comes with a "monitor" process that sits in the notification area, tells you whether Apache is running and lets you start or stop it manually.
  • If it's acceptable for your use-case, make the application a console application. You can register a handler for when the user presses CTRL+C (see Console.CancelKeyPress) that performs your cleanup before your process exits. This still won't let you handle someone killing the process from Task Manager, but it's very easy to do and might be good enough depending on your situation.
0

精彩评论

暂无评论...
验证码 换一张
取 消