Running a cleanup after a program crashes - c#

I'm currently writing quite a simple app, but it makes a change to the OS which gets changed back when the program is closed.
The worry of course, is if the program crashes. I can do everything in my power to prevent it from crashing, or handling things if it does crash - but I can't stop someone from force closing the process (unless I can?)
Is there a way to catch that event and run just a very quick cleanup before the process exits?

I don't think there is anything you can do if your process gets killed - one approach would be to have your app spawn a helper process that is just there for this case. When your app terminates that process can detect that and "fix" the OS setting as desired before it shuts down itself - obviously this only would work if that other process doesn't get killed first.

You can hook UnhandledException. You can't stop the application terminating, but you can log or do some clean up. This allows you to handle the case of application crashes.
It terms of someone actually just killing the process there's nothing you can do about that.

Program defensively.
Write the original settings to a file. Delete the file when closing. When starting, check whether the file is there - if it is, your process was killed and you know what to return the settings to.
Programming 201 - the basics of transactions, applied to system settings wit hthe program runtime as transaction boundary.

If you don't mind a little interop to C or C++ code, and if you're running on Windows Vista or newer, you could make use of the Application Recovery and Restart APIs. These APIs tell Windows to intercept your process when something catastrophic happens, so that you can perhaps call a little cleanup code before Windows kills the process completely.
See http://msdn.microsoft.com/en-us/library/cc948909.aspx.

Related

Capture .Net Console Kill or Terminate

So I have a hidden console application called Hidden.exe running.
Another application Call Killer.exe will find the process Hidden.exe or its PID, and Kills the process.
How do i programmatically capture a kill command or a terminate from Task Manager? A user can browse through the process list and 'End Task' on Hidden.exe and I want to be able to capture this event and do some cleanup before it exits.
How can i do this? I have searched around, and explored alternatives from
.NET console application exit event
Send WM_CLOSE message to a process with no window
Can I send a ctrl-C (SIGINT) to an application on Windows?
etc....
But they all dont work or only work in some cases, my case is for a hidden console application and needs to somehow capture a Kill on it. None of the above solution seem to have a 'correct' solution.
There is no such answer. A kill will always work and will fire no event. This is due to security concern to prevent virus and/or malware code.
I've since found another way.

c# windows shutdown control

Please read - this is not a duplicate.
I have a Windows service that runs under the LocalSystem acct. I am in need of restoring certain files prior to shutdown. I am able to intercept the Shutdown action at which point I initiate my restore process but the shutdown happens before I am able to complete.
I have enabled Shutdown privileges, added calls to AbortShutdown (Win32) and several other (ie shutdown /a) options but they do not work. I believe it is because the shutdown or restart has already been initiated and I have read that these functions only stop a shutdown while it is scheduled.
My goal is to intercept the shutdown, abort it, complete my tasks and then shutdown. I just need more time and the amount of time is dependent on the number and size of files I have to restore.
I am open to any suggestion and appreciate your time and consideration.
Thanks!
This sounds more like something that can be done with windows batch files.
Your goal is untenable. On Windows, the user has control over the shutdown process. If the user wants to shutdown the machine, it's not up to your software to contravene the user's intentions.
The burden is on you to make sure that your software can deal with a shutdown, whenever it happens. This usually means making sure that file operations are as atomic as possible, or using a "hot journal" file to recover (on the next system startup) in the event that atomic operations can't be completed.
The files that you speak of, that you have to restore before shutdown, should be "restored" (hard to tell exactly what you mean here) as soon as any operations are finished on them. Without further details, it hard to discuss the specific approaches.

Program works on dev machine, but won't start on test machine

I've been writing this program for a while now, and I'm finally ready to start testing it. It works 100% on my dev machine, but I wanted to try it on a machine it's never run on. So, I get my program over to a test computer. When I double-click the exe, nothing happened. I opened up task manager, and tried again. I saw the process start, but after about 5 seconds, it disappeared. No errors, no exceptions, no nothing. How would I go about trying to figure out what is going wrong? I'm still fairly new, and I've never had this happen. Thanks for any and all help!
EDIT
Sorry for not mentioning before. This is a winforms application.
EDIT 2
So, turned out what was going on is that I was trying to a dll meant for 64-bit OS into a 32-bit OS. In Windows XP, this threw a BadImageFormatException. However, in Windows 7, as I stated, it threw no exception at all.
This is a pickle, no doubt about it. I've had to debug this type of thing before.
The first bit of useful information is that no exception is being thrown out. This tells me that somewhere in your actual code is the key to solving the problem. You are either trapping an exception and closing silently, or your code is hitting what it considers to be a "normal" exit condition and is closing in what it would consider the normal way.
To figure out where and why it's exiting, I would add debug logging at key points in your application, and attach a listener to the Debug/Trace listener collection that writes out to a file. "Key points" are places where the application is supposed to exit (or the main form of the window is supposed to close), and within any "catch" block or error event handler. Run this new version on the test computer and see what it gives you. That should tell you the basic flow of the program behind the scenes, and through what mechanism it's shutting down.
If you're running a console application, it is possible that it runs and then closes itself.
Trying opening a command prompt, and then executing the application from there.
If your program has output, then you would see it in that command window.
Have you checked the application event log?
Do you have the necessary version(s) of .Net installed?
Perhaps you should put more exception handling with calls to MessageBox.Show("I failed here") through out your application.

Handling a forced exit

Is there any good way to handle a forced exit in C#?
I have a formless C# application 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.

How to handle a C# console application terminating?

If I have a console application, is there any way I can handle the following:
Ctrl-C (I know the answer to this. Using Console.TreatControlCAsInput and Console.CancelKeyPress)
Session termination, such as when someone logs off
Process exit, such as when someone uses the task manager to close the application.
I know that if I was writing a unix application, I would handle various signals to catch the request to close (SIGTERM from memory), but I also know I need to handle these messages pretty quickly and exit before the system does a kill -9 (SIGKILL).
But for a C# console application, I'm not sure how to do this.
Session termination, such as when someone logs off
Handle the SystemEvents.SessionEnded event.
Process exit, such as when someone uses the task manager to close the application.
If you mean, if someone kills the application from the taskbar, I dont think you can handle that.

Categories

Resources