C# windows application not closing - c#

I have a C# windows application. I placed it on a test server, whose set up is not controlled by my company and neither is the seurity context. I double click the exe. App runs and i see my form. I close the application, i open task manager and i still see a foot print of the applicatiion.
taskkill does not seem to remove it and it is still running in task manager.
how do i check if any resource is still being held?

The likely cause is that a background thread is still running after your application is closed. Depending on your framework and application configuration a background thread can cause a process to keep running even after the main window is closed.
Do you have any threads in your process? If so make sure to close them out when the main application window is closing. A good place to do this is in the OnClosing method of a Windows Form

Abusing Application.DoEvents() is another way to get into this kind of trouble. If you cannot kill the .exe from TaskMgr, your app is stuck waiting for a driver to finish an I/O request.

Related

Check if Windows Application is running (not process)

I am hoping to check at the beginning of an automated test if an application is open. I can check if the process is running by doing the following
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Contains(name))
{
return true;
}
}
However, the process I want to find starts up about a minute before the application actually opens and is ready to be used by the test methods (its a very slow starting application). The above code sample looks at all windows processes running, but I am wondering, is there a way to do a similar method but to look at windows applications running?
There is a method already in class Process that you can use to check if an app with a UI has fully started:
Process.WaitForInputIdle(int milliseconds)
This will wait up to milliseconds ms for the message loop to become idle (and returns a bool to indicate success status). Depending on the application you're waiting for, you might want to allow 30 seconds or longer.
This might work for you, but be aware that in my experience for some applications it is not totally reliable!
The Windows API documentation has more details about the Windows API function that WaitForInputIdle() calls behind the scenes.
When a process is started, you can say application has started.
What you want is to wait until application startup progress has completed or not.
This means, when process is started, application startup begins. When application startup is completed, is becomes ready for user input. So I think you should have a look at following question and its answers.
Programmatically, how does this application detect that a program is ready for input
Apllication is proces.
If you can modify app, at app start you can create file and at end delete it. So you can chceck file existance. If file exist app starting/started.
If you need info when main form is created use:
WINFORMS
Form.Shown event.
WPF Loaded Event
uITestControl.Exists did the trick for me.
This method will return a boolean value corresponding to the existence of the application window being open. This allows an if statement to be created that can open the application if not already open, or do nothing if its already open.

Is it possible to fire any event in c# application when the application is terminated from taskmanager's process?

I have a c# form application. when this form is closed from task-manager's process i have to do something in my Form application. is it possible?
I apologies if i mislead anything. but i need this solution.
No you can not. What you can do, in order to track this kind of situation, is on startup create some hidden file in directory where you guaranteed by the OS for write permit and on the close of your application, delete that file.
In this way, if on startup of your app, you will find hidden file, that will mean that application was closed non in normal way. So you can execute some actions accordingly.
Hope this helps.
The task manager will try to close your application gracefully first. You will get a normal close signal that you can act on. In a Forms Application that probably corresponds to the OnClose/Closing of the main window. If this signal is not used to end the application in time, the task manager will kill the process. You will not be able to intercept that or act upon it.
Based on what I know, Killing a process with Task Manager is immediate.
The application is not able to get informed in any way.
Task manager generally call the Windows API ExitProcess to kill the process.
On how to hook API, you can refer to:
http://www.codeproject.com/KB/system/hooksys.aspx
SOURCE
In alternatve, you could create an additional process which obsverve the main application and if he find that the application is closed then do something. If the main application is closed normally, then the process is killed from the main application. thiS could be an easy workaround.
"No you can't, what you can do though is do something just before the form is disposed. msdn.microsoft.com/en-us/library/…. What exactly are you trying to archieve? –"
UPDATE
Based on your response to my comment:
What if you do something else. Create a windows service (daemon) that checks when your form is open (windows name) and then monitors the form to check when it is closed, and when that happens it calls the web service you need.
Your windows service would be as simple as this:
Thread thread = new Thread(() =>
{
while (!formClosed)
{
if (!Process.GetProcesses().Any(x => x.MainWindow.Title.Contains(windowName)))
{
//form closed, call your web service
}
Thread.Sleep(5000);
}
});

Exiting a C# winforms application

I have an application that imports data from Excel. However, when I run the winforms app and I intrupt the application, using System.Windows.Forms.Application.Exit(); I can still see the "MyAppName".vshost32.exe running in task manager.
When I exit the application in debug mode, the form closes, but the VS IDE is not "stopped".
How do I ensure the application ends correctly.
Your call to Application.Exit() is working fine. The MyAppName.vshost32.exe executable is a host for debugging purposes. It runs whilst you have a project open in Visual Studio, regardless of if there is an active debugging session.
Update: Ok, I misunderstood. The above is true, but you're probably having problems with hung threads in the background. You need to terminate your threads to make it close properly. Asher's answer covers this. If you're just trying to do a super-hacky quick-and-dirty kill, you can use the following (though I take no responsibility for side effects, since it's extremely hacky):
System.Diagnostics.Process.GetCurrentProcess().Kill();
The process doesn't terminate because it still has foreground threads running.
If you create threads in your application you need to mark them as background threads or make sure they terminate when you want the application to exit.
Have you tried the more brutal Environment.Exit() function?
Application.Exit() just sends a message saying to shutdown; if the message never gets processed (for whatever reason), the application will stay running indefinitely.
From the MSDN documentation of Application.Exit():
The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.
I had a similar problem caused by a third party tool that did not allow me to set the threads as Background. Polynomial had the right idea, but then syntax is like this:
System.Diagnostics.Process.GetCurrentProcess().Kill();

How to keep process running after closing the program?

I am now developing an application on Windows Mobile 6.5 with .Net Compact Framework 3.5 using C#. There is a function in the program that I use it to update the location information periodically from server side, but if I keep running this computation, it would cost too much energe. For this reason, I want to run it in background and I try to use BackgroundWorker to do this and it works well.
The problem I have now is that I can't minimize the program so that I have to keep the main form of the program run in foreground even if it's not doing anything and this is very inconvinence for a user. However, when I close the program, the BackgroundWorker will also be closed.
Is there any method to keep the update process running (somewhere in memory or so) when I close the program? and then can restore the information when I restart the program?
How about creating a Service instead of a background worker?
If your Form closes, then Application.Run (probably called over in Program.Main) returns and the process' primary thread exits, causing the application to terminate.
The solution, then, is don't close the Form, simply Hide it. By default the "MinimizeBox" property for your Form should have been true and it should have an [X] in the upper right corner. Clicking this minimizes the Form and will not exit your application.
The other option in some cases is to not have a Form at all. The challenge here is that the CF doesn't have any Application.Run overload that doesn't accept in a Form (like the desktop framework does). The Smart Device Framework does provide one if you want to go that route.
I have not used the .NETCF 3.5. However in the previous version on .NETCF 1.0/2.0 I observed that even if you close the application using (X) button, it just goes to background but remain in the memory.
If that is the case with .NETCF 3.5 as well then I think you do not need to anything here. The background worked will be running even if you close the application.
I Hope this will help you.

Why does my application not close on logoff/shutdown (c#/.net winforms)?

My winforms app isn't shutting down nicely when I log off/shutdown. I have a main form, whose Closing event is fired correctly, but there must be something else keeping my application around. If I check Application.OpenForms there's just my one main form.
The tricky bit, and where the problem probably lies, is that my application uses ShellWindows to hook into Internet Explorer, and occassionally opens up forms when IE events fire. It's after one or more of these forms has been opened and closed that my app stops closing on shutdown.
I think I'm cleaning up all form objects etc and calling FinalReleaseComObject() appropriately, but I guess there are references somewhere that are holding my process open. Is there any way to work out what it is that's stopping my app from closing gracefully?
An application will also stay open if there are threads running that have not been set to background. If you are creating any of your own threads, make sure that they are terminating appropriately.
If it is not critical that the thread finishes, set IsBackground to true. You can also call Abort on a thread to (somewhat)forcibly kill it.
The most likely cause is that you have a background thread hanging around that is not being closed when the main window of your application is closed. Depending on your settings and framework version background threads can keep an application alive when the main thread is terminated.
During shutdown windows asks every running app to terminate usually by sending a WM_QUIT to the main window on a process. WinForms will happily use this message to shutdown the main window but if any background threads are left the actual process could continue.
This is a really ugly way to do this, but if all you want to do is kill any thread that's hanging around, you can get all the threads running in your application with System.Diagnostics.Process.GetCurrentProcess.Threads, and then enumerate through them and call Thread.Join() or Thread.Abort() on them.
Just make sure to NOT call .Abort() on the main (UI) thread that you're working from (the one that receives the Closing event). So make sure to check that your current thread (System.Threading.Thread) is not the one you're aborting.

Categories