Who is calling the Main () method in C #? How to exit the application in case of an exception in the Main () method?

I was looking at some other question, and then I had this question:

  • Who is calling the Main () method?
  • If I want to exit / exit the application (when I get some kind of exception in the Main () method itself), is it advisable to use the instruction return;from the block catchin the main ()?

    • Note that I do not start the thread in the Main () method explicitly. When we launch the application, are there any threads starting automatically in the background?
    • Application.Exit() does not guarantee application shutdown
    • ( EDITED point ) Environment.Exit()is another option.

Can I use the instructions return;to exit the application? If not, what are the (subtle) things that might make this a bad idea?

By comparison, is this the best approach to exit?

+3
source share
5 answers

If your application is terminated due to an unexpected error, you can use Environment.FailFast , which will “crash” the application with the specified message, which is recorded in the event log and gives the user the opportunity to send data about the accident to Microsoft. As a developer, Microsoft can provide you with crash data.

(, ), , int, , .

+2

Main()?

CLR

/ ( - Main()), return; catch Main()?

, , .

+1

try/catch Main() AppDomain.UnhandledException. , Environment.Exit, Application.Exit, , , . Environment.Exit , 0, ( ), void Main() int Main().

+1

Application.Exit () for forms-based applications. The best way to handle exceptions in Main:

static void Main(string[] args) {
    try {
        // code here
    } catch {
        // do any clean up and return

        // optionally specify an exit code
        Environment.Exit(1 /* or any number other than zero since this is an error condition */);
    }
}
+1
source

1) The OS basically calls the Main method. This start address is the PE .exe header (if I remember correctly).

2) Yes, use the operator returnfrom the block catch.

0
source

All Articles