13

I am maintaining an existing C# application, and I noticed the following code are not working as expected.

 private void Form1_Load(object sender, EventArgs e){
 ...
 if (proc.Length == 0)
 { 
 proc = Process.GetProcessesByName("OpCon");
 if (proc.Length == 0)
 {
 WriteLog("DataloggerService start: no TSS process detected; close;");
 this.Close();
 }
 }
 ...
 }

The code is supposed to exit after the Close() api call. However, it still proceed.

After some reading and research, I modified it to

 private void Form1_Load(object sender, EventArgs e){
 ....
 if (proc.Length == 0)
 { 
 proc = Process.GetProcessesByName("OpCon");
 if (proc.Length == 0)
 {
 WriteLog("DataloggerService start: no TSS process detected; close;");
 this.Dispose();
 Environment.Exit(0);
 }
 }
 ....
 }

It seems to exit as expected. However, I am not confident whether this is the best practice?

is it really necessary to call this.Close() or this.Dispose() before Environment.Exit()?

Thanks.

regards, Sqr

asked Oct 16, 2014 at 2:25
3
  • 1
    See this: stackoverflow.com/questions/3880836/… Commented Oct 16, 2014 at 2:30
  • Are you talking about Winforms or WPF application because in latter, default constructor is the method to be called Commented Oct 16, 2014 at 2:57
  • in WPF application, you should not call Window as Form. Commented Oct 16, 2014 at 3:31

1 Answer 1

32

In your WPF application whenever your MainWindow that is specified as StartupURI in App.xaml is closed your application exits automatically.

Still if you want to handle this exit of application on your end you can go for below solution.

Override the onClosing of MainWindow and manually exit/shutdown your application.

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
 // Shutdown the application.
 Application.Current.Shutdown();
 // OR You can Also go for below logic
 // Environment.Exit(0);
}
ProdigioM
47410 silver badges24 bronze badges
answered Oct 16, 2014 at 4:23
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.