Reputation: 427
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
Upvotes: 13
Views: 30695
Reputation: 946
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);
}
Upvotes: 32