Imagine launching a process or start an application, however in task manager makes a kill this process. Is there an event associated?
This code, cancel the user close the window application
private void Form1_Aplicacao_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
e.Cancel = false;
}
But if I using process.Kill() method, FormClosing event has not been fired.
My question: Have an event to get a kill this own process?
No event is raised when a process is killed. Most likely, when killed the process is simply removed from the scheduler's list of runnable tasks, its memory is deallocated, and then the OS picks up any remaining pieces afterwards. I would definitely not count on even destructors or garbage collection running, so any resources which are in use that the OS cannot clean up will be leaked.
(Actually) killing a process means that you slay it, slice it up, grind it, and toss the pieces into the ocean. More technically, no jump into the killed process' code is issued, so there can be no event fired inside that code. Remember that events, like a lot of other flow-control constructs (loops, conditionals, etc) as well as multitasking itself, are just fancy gotos. Very useful fancy gotos, admittedly, but still simply jumps to different parts of available code.
Short answer: no, there is no way for your application to be aware (for instance with an event that is raised) that its hosting process has been brutally killed.
It's not quit right.
You can use process communication Technics such as PIPES.
You can send throw PIPES and wait for answer.
You can create a rule that if answer hasn't been received in X time, the process has been killed.
But this in just one of the process communication options, for more information you can check in the following link: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365574(v=vs.85).aspx
Also look at the following option:
C# process.start, how do I know if the process ended?
Related
Following are the ways by which we can exit an application:
Environment.Exit(0)
Application.Exit()
Form.Close()
What is the difference between these three methods and when to use each one?
The proper method would be Application.Exit(). According to the Documentation, it terminates all message loops and closes all windows thus giving your forms the possibility to execute their cleanup code (in Form.OnClose etc).
Environment.Exit would just kill the process. If some form has e.g. unsaved changes it would not have any chances to ask the user if he wants to save them. Also resources (database connections etc.) could not be released properly, files might not be flushed etc.
Form.Close just does what it says: it closes a form. If you have other forms opened (perhaps not now but in some future version of your application), the application will not terminate.
Keep in mind that if you use multithreading, Application.Exit() will not terminate your threads (and thus the application will keep working in the background, even if the GUI is terminated). Therefore you must take measures to kill your threads, either in the main function (i.e. Program.Main()) or when in the OnClose event of your main form.
they are all fine.
but form.Close() won't close your application
it closes the form and after that
the main-method returns an int (exitcode).
if you want that your application exits with exitcodes use
Environmet.Exit(exitcode) or return the exitcode in the main-method
Is it possible for a running c# application to start/invoke some new arbitrary process, but only do so after the current running application is terminated?
I guess it's possible to call the new process from Process.Start() via cmd.exe and do something like sleep 3 & c:\mynewapplication.exe - this would giver the 'caller' some three seconds to terminate itself.
However this is a bit hacky, and was wondering if there was a neater way?
Depending on the type of application, you could simply listen to the end of the program. One option you have is the Application.ApplicationExit event.
Another possibility is to start another process, that waits until the first process dies. You could poll Process.GetProcesses for example. This will raise the event, even if the first process crashes. You could also register the Process.Exited event.
It has little to do with C#. It is a question about the Windows OS, and, in particular, in WinAPI.
Generally, the only 'thing' that runs code is threads. When your process in terminated, all its threads die.
Your best approach is probably by starting a process that will wait before starting your new process, as you suggested, however you may, for example, hook on some of the functions called when something happens and start your new process there.
I know this won't work in all scenarios, but please keep in mind the following 3 scenarios:
An IIS reset - if the code is running inside IIS
A Server restart or shut down
User closes the app (if its a Windows form or Console App).
Lets say I have a code block that runs a loop. Is there a way to ensure at least that the current loop item gets processed before the app shuts down.
Like this...
Loop runs: 100 items, app gets shutdown (for reasons above), app is busy with item in loop 53 for example. It first finishes all code for that item between the foreach... and then allows the app to gracefully shutdown.
Is this type of thing possible?
Nothing I would do but If it is ok to abuse the system you might be able to use the CriticalFinalizerObject
It is guaranteed to execute
even in situations where the CLR forcibly unloads an application domain or aborts a thread
I really don't think so. You are stuck in front of windows. Windows take that kind of decisions for you.. IF somebody is shutting down the pc, then you are just shut down. This is the same scenario as if they where a power failure. What will you do in that case?
For a normal application: While your code is running in a foreground thread (not ThreadPool or Thread.IsBackground == true) it will not be aborted mid-execution, unless the user forcibly quits the process.
If you are running your loop in a background thread, you can try handling the exit event of the application, waiting for the loop to finish or at least reach a stable state before being aborted.
In most apps you can handle close event and not allow it but you can't do anything when user decides to kill your process. So i would say that its not possible.
How about doing this. using a try catch and finally in the static void Main
Here even if you end task the application, finally will run. not sure about power failure.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
finally
{
MessageBox.Show("I run always.");
}
}
Hope it helps
I have some really big application mixture of c# and j#.
Sometimes when I close it, there are some threads that are not closed and they are hanging in the task manager and it is impossible to kill them from there.
I have really problem to find all those threads and add them to the closing event .
Is there some way violently kill all threads that were opened by application in the closing event ?...
Thanks.
Is there maybe some Tool that can tell me what threads are opened while i close the application and who openned them ?
This shouldn't be happening, and if it is, you're trying to address it the wrong way.
When your application exits, the .NET Framework will automatically kill any threads whose IsBackground property is set to "True". Designate each of your worker threads as background threads, and you won't have this problem anymore. Taking advantage of the BackgroundWorker class and the ThreadPool class, which automatically create background threads, is a much better option.
Otherwise, you need to clean up your foreground threads explicitly. A properly designed application will do its own bookkeeping and have a deterministic, structured way of ensuring that all its threads have been closed before exiting the Main method. This is what you should be doing anyway if your threads require a graceful termination.
Killing the process is a very bad idea, as is letting your threads run about willy-nilly in your application.
You can use : Environment.Exit(0); , that will shutdown the application if threads are running and wont cause any problems.
You should close your threads gracefully, but just want you and others to know the way that is not recommended but possible:
on your OnClose Handler:
System.Diagnostics.Process.GetCurrentProcess().Kill();
I totally prefer Cody Gray way of doing it.
Well, you could call Application.Exit() but that won't be of much help.
The bottom line is that you have to gracefully close all of the threads yourself if you want to do things properly.
My 2 cents... to all answers...
Try to force SHUTDOWN
Put into void CurrentApplication_Exit(object sender, ExitEventArgs e) and private void Window_Closing(object sender, CancelEventArgs e) those lines
System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
System.Windows.Application.Current.Shutdown();
internal void Close()
{
Dispatcher.CurrentDispatcher.Thread.Abort();
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
Application.Current.Shutdown();
}
I was having similar issue while closing form/application. It was not really exiting from the debug mode and comes to the design mode. Following resolves my issue.
Followed the link.
Windows Form Application, Thread won't stop
Step one did not resolved it.
Environment.Exit(0); - Resolves and worked fine.
Right now I am using Process.Kill() to kill a process. Is there a way though, instead of just killing it immediately, that I can like send a message to the process instructing it to close so that it can gracefully clean up and shut down. Basically, I'm looking for the equivlent to just clicking the red X in the upper right hand corner, which I believe DOES send a message to the application requesting a shut down.
If the process has a windows interface (as you refer to the red "X"), you can try Process.CloseMainWindow(). If it fails, you can fallback to Process.Kill().
Killing can not be graceful, perhaps you can signal the process to commit suicide.
For signaling you have many options.
SendMessage
NamedPipes
Named Mutex
Sockets
It would depend on the process you're killing. As stated at on the relevant page for Process.Kill, "Kill is the only way to terminate processes that do not have graphical interfaces." If there is a graphical window, then go with the answer by lc above; Process.CloseMainWindow functions as the red X you referred to.