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
We can close the window either by using "this. Close()"or by using "App. Current. Shutdown()".
The proper way to shutdown a WPF app is to use Application. Current. Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can't be canceled.
WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With