Как завершить программу c

от admin

Exit Console Application in C#

This tutorial will discuss methods to exit a console application in C#.

Exit a Console Application With the return Method in C#

If we want to exit our application, we can use the return statement in C#. The return statement ends the execution of a method and returns the control to the calling or the main method. We can use the return statement inside the main() function to end our console application’s execution. The following code example shows us how to exit a console application with the return statement in C#.

We exited the console application with the return statement in C# in the above code. The above code only prints HI because the application execution ends before the line Console.WriteLine(«Hello»); gets executed. The only disadvantage of using this method is that we cannot exit the application from any other function.

Exit a Console Application With the Environment.Exit() Method in C#

We can also use the Environment.Exit() method to exit a console application in C#. The Environment.Exit() method is used to end the execution of a console application in C#. The Environment.Exit() function returns an exit code to the operating system. See the following example.

In the above code, we ended the execution of the application from the func() function with the Environment.Exit() function in C#. The advantage of this method over the previous method is that we can exit the application from any function.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

How do I properly exit a C# application?

I have a published application in C#. Whenever I close the main form by clicking on the red exit button, the form closes but not the whole application. I found this out when I tried shutting down the computer and was subsequently bombarded by lots of child windows with MessageBox alerts I added.

I tried Application.Exit but it still calls all the child windows and alerts. I don’t know how to use Environment.Exit and which integer to put into it either.

Also, whenever my forms call the FormClosed or FormClosing event, I close the application with a this.Hide() function; does that affect how my application is behaving?

4 Answers 4

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

Читать:
Формула в excel впр как суммировать подходящие значения

I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.

When IsBackground is false it will keep your program open till the thread completes, if you set IsBackground to true the thread will not keep the program open. Things like BackgroundWoker , ThreadPool , and Task all internally use a thread with IsBackground set to true .

By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?

In short, yes. The entire application will end when the main form (the form started via Application.Run in the Main method) is closed (not hidden).

If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don’t intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.

If you want to be able to have the user click the «x» for your main form, but have another form stay open and, in effect, become the «new» main form, then it’s a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you’ll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you’re in then you’ll need to add more details to your question describing what types of applications should and should not actually end the program.

Функция exit

Функция exit выполняет немедленное завершение программы. Завершаемый процесс, как правило, выполняет очистку используемой памяти. Во-вторых, все функции, зарегистрированные вызовами atexit , выполняются в порядке, обратном порядку их регистрации. В таком случае, все используемые программой потоки закрываются, и временные файлы удаляются, и, наконец, управление возвращается ОС или другой программе.

Аргумент параметра value возвращается принимающей стороной (ОС или другой программой).

std::exit

Стек не раскручивается: деструкторы переменных с автоматическим временем хранения не вызываются.

Взаимосвязь с основной функцией

Возврат из основной функции либо с помощью оператора return , либо по достижении конца функции выполняет нормальное завершение функции (вызывает деструкторы переменных с автоматическим временем хранения ), а затем выполняет std::exit , передавая аргумент возврата оператор (или ​0​ ​, если использовался неявный возврат) как exit_code .

Похожие статьи