Exiting a C# winforms application - c#

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();

Related

How to tell if my application has been removed from the clipboard listener chain?

I am writing a small utility application to monitor my clipboard. This at current works quite well, but a friend has told me that it randomly will stop showing alerts upon clipboard change, and that restarting fixes it.
I couldn't reproduce, but eventually I ran into it myself - the application had stopped recieving WM_DRAWCLIPBOARD events.
How can I tell when my application has been removed from the listener chain?
This is one of the hazards of the clipboard listener chain: One bad application can damage the chain. Instead of using the SetClipboardViewer function, use AddClipboardFormatListener which does not have this problem.
If you are debugging an application that uses SetClipboardViewer and the application crashes or you stop the application in the debugger, or in some other way bypass the restoration of the clipboard chain, there is performance degradation in Windows, to the point that seemingly unrelated features of Windows, such as Alt-Tab, or restoring a minimized window, stop working. They come back if you restart Windows.
An application that inserts itself into the clipboard chain this way should be calling ChangeClipboardChain during Dispose of the main form, or at another appropriate time, to avoid this issue. Dispose isn't called if you stop the app in the debugger.
I have not tried AddClipboardFormatListener; first time I've heard of it; I'm going to try it to see if I can avoid the issue in my own app while I'm debugging.

How do I make a console application appear "Not Responding"?

For testing, what is the easiest way to make a program appear "Not Responding"? Interrupt Windows messages or put it in an infinite loop?
I have tried a simple loop like
while(true)
But that does not work.
The test application is a C# console app. Does the fact that it's running in a console make it "more responsive"? Perhaps there are some parts of the added console handling that make it respond all the time?
Update:
Changed it to a simple Winform Application put that into an infinite loop. Worked lika a charm. Thanks to Servy.
A console application will never be "Not Responding" from the point of view of Windows Task Manager. In reality task manager isn't running your program, it's running a shell (cmd.exe) that is running your program, and that shell is written such that it will always be responding even if your program isn't. If you aren't running your program through a shell but are starting it directly, then there won't be any UI for the program and it won't be an "Application" in task manager (meaning it won't show up in the "Application" tab), it will just be a process.
If you just need to mimic any program "Not Responding" from the point of view of task manager you should make a simple winforms application and put that in an infinite loop. If there is some obscure way of making a program appear "Not Responding" from a console app, at the very least it will be much harder than from any of the standard desktop GUI types.
You could do a Thread.Sleep(X)
The easiest way to make a program 'not responding' indefinitely is to use an infinite loop:
while(true);
Do any work on the UI thead (for a UI application)
Thread.Sleep
While (true)
this might give some insight into more of what your trying to accomplish (.net console app stop responding when printing out lots of chars in a row)

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.

C# windows application not closing

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.

Why does .exe refuse to stop?

I've "inherited" a legacy C#/C++ program that I have to debug. The current problem is that the .exe won't stop after I close the program, i.e. it still shows up in Task Manager.
This is a problem, because it won't let me restart the program, because only one instance can run. Often killing the process doesn't work; I'm forced to reboot.
I was under the impression that when the main program stopped, all the child threads were also supposed to stop, but I may be wrong.
Q: What would cause a .exe to not stop?
Child threads will not stop automatically unless they have been specifically set as background threads (i.e., with thread.IsBackground = true).
Edit: It is also possible that the main thread isn't terminating when the form is closed (i.e., there's other code that is set to run after close that isn't completing).
I find it useful to attach to the running process with the debugger and press the pause button. After that I would inspect the Threads window and see what the stack trace is doing for each of the executing threads. The threads window is hidden by default. Here is more information about how to show it and use it:
http://msdn.microsoft.com/en-us/library/w15yf86f.aspx
My guess would be that all threads aren't stopped. Usually you can end task the program and it will stop though. Maybe one thread has hung on to a system resource that's more difficult to release.
If you can get a debug build, run the program and after the program is "exited", hit the pause button in the debug window. At that point you can look through the threads and find out which one is hung. To help, you should name your threads when they get created (it's an extra parameter in the .Start function)
You may want to look into process explorer. It makes it easier to shut down the programs and it can view the threads of the program and potentially point you in the right direction of where to make the the program behave.
At the most frundamental level, there is an infinite loop somewhere.
Is the startup form the one that's being closed to exit the application? If it isn't you need to put Application.Exit() or Environment.Exit() in the form.closed event of the form that is closing last.

Categories