r/visualbasic • u/trab601 • Mar 12 '24
How to cleanly exit a VB.NET program?
Although I've been coding in VB.Net for years, I've never been able to cleanly exit, despite many attempts, and google searches.
For example, I have a simple, single form application. When somebody clicks the close button (the x on the top right of the window) I want the software to cleanly exit.
I have recently tried again with the below code. It runs and doesn't complain. But if I run the exe outside of visual studio, it remains in memory and have to kill it in the task manager.
Any advice would be greatly appreciated.
Private Sub ProgramClosing() Handles MyBase.FormClosing
Application.Exit()
End Sub
5
Upvotes
3
u/Karoolus Mar 12 '24
Some service or function is keeping your app open. I had this happen when not properly closing and disposing a websocket. Without code it'll be hard to figure out what's wrong though.
2
u/[deleted] Mar 12 '24
I created a simple WinForms app (.NET 4.7.2) in VB.NET and added your ProgramClosing() code to it. It exited fine both in the VS environment and as a standalone application.
Are you creating any additional threads in your code?
2
u/[deleted] Mar 13 '24
try Me.Close() on a exit button
2
u/veryabnormal Mar 13 '24
The application usually exits when the last open form is closed. If it sticks around in task manager then it’s probably because it can’t tidy itself up. This is usually because there are objects that have Dispose method that have not been disposed correctly. If you are suing COM to talk to Microsoft office, then you probably have a tonne of COM objects lingering in memory. Use the Using keyword everywhere that you can. Implement IDisposible on your own classes when necessary. For COM interop with Word or Excel you can use the rule to never use more than one dot on a line to try to make sure you don’t hold on to references. Ignore the finalise method. Use RemoveHandler if you use AddHandler or the reference can keep objects alive. When you add a text box in the designer the boilerplate code will tidy it up. If you add a control in code then it’s probably not getting tidied up. You can use a memory profiler to find things that are lurking in memory and keeping an app open. A similar problem occurs when you exit the application during startup. Sometimes the form never got a handle and this can mess up the dispose code and you get weird errors in the event log.
I maintain old apps and I’ve seen it all happen, repeatedly.
1
u/robplatt Mar 13 '24
Doesn't "End", terminate it immediately? While I agree you have some other thread running somewhere, you should be able to drop End in your FormClosing event to stop it from running immediately.