This question already has answers here:
How do I properly exit a C# application?
(4 answers)
Closed 6 years ago.
I used to call Application.Exit terminate my application. At some point in time, I start to use a DLL, and I cannot fully terminate my application (a thread is running).
However, I can call Environment.Exit(0) and terminate my app completely.
I have read some useful posts.
[Closing Applications
[http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx][2]
It seems
Application.Exit() is recommended for Windows application and
Environment.Exit(exitCode) is recommended for console application
That's what I read from other posts.
===== The reason that I asked this question, and Something is still unclear to me:
Now, I just add Environment.Exit(0) at the end of Application.Exit event handler, since I had the event handler for Application.Exit and save some state information in the handler.
I am still not sure that I use this in a correct way. In other words, does this make sense to call both Application.Exit() and Environment.Exit(exitCode)
If you really just needs to terminate the App instantly and terminate all the threads, then you need to use Environment.Exit(0).
If you want your Forms' Close events to fire and your threads to continue their work, you need to use Application.Exit();
It really depends on your situation. The first is like you terminating the process (Killing it). The Second is like sending a message to the App and politely asking it to finish everything in hand and then close for good. This allows to save some state information by firing the closing events if implemented.
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
This question already has answers here:
How is this possible: OnPaint processed while in WaitOne
(2 answers)
Closed 4 years ago.
There's some non-optimal code in a program like this (Pseudo code to give you an idea):
public void button1_click()
{
picturebox1.Image = someBitmap;
someBitmap.LockBits(...);
Parallel.For(..., () => DoSomethingWith(someBitmap));
someBitmap.UnlockBits(...);
}
From time to time, the program crashes, saying that the bitmap is already locked. I don't need debugging help and I don't need code to fix the problem. I can easily fix it.
What bothers me more is the fact that I don't understand how that can happen. IMHO the UI thread is blocked. No windows messages should be able to be processed while the button1_click method is executing. Unless, of course, someone calls DoEvents(), which is not the case.
Still, when I look at the call stack, it shows this:
As you can see, the Parallel.For() call is still on the stack. It's not completed yet. The .NET code reached a ManualResetEventSlim and should be waiting. From MSDN I can't see that the Wait() methods do message dispatching.
Still, at that point, a WM_PAINT message got processed, causing the picture box to access the bitmap while that bitmap is still locked by LockBits().
What's going on here? Where's my understanding of UI thread blocking wrong?
#Dai asked whether this only happens during debugging. Indeed that seems to be true. I gave it 10 runs and it never crashed. So it seems the debugger is not my friend this time.
There are several ways to achieve this:
Can You Execute Code While Waiting For A Lock?
Unexpected Window Message Pumping Part 2
When you are waiting some messages are still pumped. This includes COM messages which are seemingly also used by the debugger.
The message pumping behavior of Windows Forms and WPF has changed several times since .NET 4.0. It can hit your application at any time if you are called via UI automation libraries if you have pending posted messages.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Application.Exit
I have a Winforms app in which Application.Exit() fails to run.
public Form1()
{
InitializeComponent();
path=parseINI();//Gets path from ini file
}
In my case, Application.Exit() is being called from the parseINI method, where it doesn't work. Is the problem that its being called when the app is starting? I stuck it in another method that runs after the form is loaded, and it works there. I did use Environment.Exit in my parseINI method, and that worked (despite it being for console apps rather than WinForms).
EDIT: I should probably add that its there as a check, to make sure a file being read is formatted correctly, if it is, then its not called, otherwise the program exits.
This might be because you still haven't started the application via Application.Run when the Form ctor executes.
The common startup code template goes like this:
Application.Run(new Form1());
If that is the case, you call Application.Exit before Application.Run. So after you have called exit, you effectively call Run, and therefore, the application runs.
Call the Form.Close() method inside parseINI() instead of Application.Exit()
The Environment.Exit() method terminates the application, closing the application thread. Indeed, from the documentation:
Terminates this process and gives the underlying operating system the specified exit code.
Why do you have to shutdown your application from within your parseINI method?
Anyway, the method call for Application.Exit() is not working for you, because, reading the MSDN page:
This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread.
Then, you can add this line to your constructor, to "run" the application, allowing you to use Application.Exit():
Application.Run(new YourForm());
You can find an interesting discussion here: http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx
Read this answer for details.
Furthermore, read this important SO question to better understand the difference between Environment.Exit() and Application.Exit().
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
I have a Windows Mobile program that accesses an attached device through a third-party DLL. Each call to the device can take an unknown length of time, so each call includes a timeout property. If the call takes longer than the specified timeout to return, the DLL instead throws an exception which my app catches with no problem.
The problem that I have is with closing the application. If my application has made a call to the DLL and is waiting for the timeout to occur, and I then close the application before the timeout occurs, my application locks up and requires the PDA to be rebooted.
I can ensure that the application waits for the timeout before closing, under normal conditions. However, I am trying to use AppDomain.CurrentDomain.UnhandledException to catch any unhandled exceptions in the program and use the event to wait for this pending timeout to occur so the program can be closed finally.
My problem is that this event doesn't seem to stick around long enough. If I put a MessageBox.Show("unhandled exception"); line in the event, and then throw a new unhandled exception from my application's main form, I see the message box for a split second but then it disappears without my having clicked the OK button.
The documentation I've found on this event suggests that by the time it's called the application is fully committed to closing and the closing can't be stopped, but I didn't think it meant that the event method itself won't finish. What gives (I guess that's the question)?
Update: In full windows (Vista) this works as expected, but only if I use the Application.ThreadException event, which doesn't exist in .Net CF 2.0.
I came across this problem as well. This is a known issue in .NET CF (v2.0), but I also had it while using v3.5 (although the situations in which it occurs are more specific). You can find the (old and still active) bug report here.
Calling MessageBox.Show() causes it to close immediately, but in my case there were two workarounds:
1) Call the MessageBox.Show() a second time. It then does block until closed by the user. You can check the first MessageBox.Show() closed prematurely by checking the DialogResult. I don't remember which result it returned exactly when it failed, I remember it giving a non-default result.
2) Create a custom Form and call ShowDialog() on that. It worked for me, but others have reported it doesn't work. You could also call Show() and make it blocking yourself (don't forget to call Application.DoEvents() so it keeps processing events).