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.
Related
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?
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
After I close the main window of my program, the process is still running in the background.
How can I check what is the cause for this weird problem?
(I don't know which part of my program code is relevant)
First check that the value of your application's ShutdownMode property is equal to ShutdownMode.OnMainWindowClose -- if it is not, see if the actual value is preventing the app from closing.
If this does not solve the problem, then you have one or more non-background threads still running after the main window closes, preventing the process from shutting down. Break into the debugger and see how many threads are still alive and what they are doing; this will lead you to a solution.
To see the Thread that is currently running and stopping your application from termination just press "Break All" at the Visual Studio and see where the cursor stops.
Note: you can force application to terminate by calling Environment.Exit();
Another reason could be that someone set the Application.ShutdownMode to OnExplicitShutdown.
One possibility is that you create threads which are not set to background or you're calling code that does that; that may keep your process "alive" even after you shut down your main thread.
Make sure that you terminate all of your threads before you exit or you set their IsBackground property to true.
We have an application written in .net, c#, winforms. We noticed that sometimes when closing the application, the process remains.
I'm not sure how I can reproduce that behavior, so I'm looking for some clues as to why the application wouldn't exit.
The application uses a bit of background threads. Thread pools. Wondering if that could be the cause. Anything else could have this effect?
If you have thread's that have IsBackground property set to false that are alive after application is closed, they will remain
The application uses a bit of
background threads. Thread pools.
Wondering if that could be the cause.
Anything else could have this effect?
It most definitely could be the cause though I cannot be certain that it actually is. One way to test this hypothesis to make sure all threads that have been explicitly created are designated as background threads. This can be done by setting Thread.IsBackground = true which will allow the application to terminate if the main thread ends. If there is at least one thread for which IsBackground = false then the CLR keeps the host process running.
Its likely to be a thread left running. If you have a look at the process in task manager you can see when a thread starts, and how many are left running when it exits by adding the 'Threads' column from the view menu.
I would start by making sure you start and end on the same thread count.
Get Process Explorer and possibly Process Monitor and see what thread is left suspended or running.
If you are able to run in debug and you close the form, VS should not return to the normal code edit mode (it will still have the pause and stop buttons from debug active). You can then press Pause and check the Threads window to see where the call stacks are stuck for threads that are still active.
I'm trying to figure out a way to make user controls run in their own UI threads. Is this possible? I'm trying to prevent a module-based application from crashing due to a single module.
Any thoughts?
That's not possible. However, with some non-trivial code, you can have different windows running in separate threads. Each window will have its own message loop.
Update:
Another way you could think of is to write your controls in a special way. You can handle all events in your controls by creating a new thread that will run all the logic.
Unfortunately all UI controls run on the same UI thread. Therefore any code running on this thread that could potentially lead to a hang situation would need to be coded with some sort of timeout logic.
DateTime startTime = DateTime.Now;
while(DateTime.Now.Subtract(startTime).TotalSeconds < 30)
{
//do something
}
Otherwise, as Orlangur stated earlier, all event handler code would need to be run in separate threads. You would still however need to monitor these threads to determine if they've been running too long and shut them down. As such you might as well implement the type of logic above as it would be a lot less work and more maintainable.
I suppose it's not a matter of the program crashing. Exceptions can be caught of course, but the issue is in hanging controls. For the sake of this situation, here's an example:
public void Button1_Click(object sender, EventArgs args)
{
while(true) {}
}
If this code were to run in a control, an exception wouldn't throw, but it would hang. I'm trying to determine a way to catch this and remove the control module from the application.
Running controls in different threads should be possible. A little hacking and windows overrides and it should be doable.
I am thinking you can create a GUI control in another thread, then move it to a common window (main gui thread) with the win api SetParent. SetParent can be used to "hijack" other windows, so you should be able to grab the controls this way. But of course there might be focus issues and other issues, but might be doable.
I used that once to put my own button onto MS Messenger.