Reputation: 19661
When calling Close()
method, the form does not close immediately. It has to wait for other code (e.g: all running methods) to be completed. Note: this behavior doesn't occur on the main form.
What I want to achieve:
Private Sub Dummy()
If foo() Then Close()
If bar() Then Close()
'Other code that shouldn't be reached
'if 'foo()' or 'bar()' returned true.
End Sub
I do NOT want to call foo()
and bar()
, check for both values, and then call Close()
.
I know that I can do something like:
If foo() Then
Close()
Exit Sub ' Or (Return)
End If
But I'm looking for something simpler and -preferably- will close the form immediately without returning to the caller method if there's any.
Upvotes: 1
Views: 394
Reputation: 11801
As the other's have stated, there is not a easier pattern than that which you have posted.
If we have method A() that calls method B(), and want to call Close() from method B(). In this case code in method A() will still be executed.
If you want to exit out of MethodA if the form has been closed in MethodB, you can check the form's IsDisposed
property. It will be True
after calling Form.Close
. Alternatively, you could check the Form.Visble
property in MethodA; it will be False
if the form has been closed.
Something like this:
Sub MethodA()
MethodB()
If Me.IsDisposed Then Exit Sub
' some more code to run if Form is not closed
End Sub
Sub MethodB()
If foo() Then
Me.Close()
Exit Sub
End If
If bar() Then
Me.Close()
Exit Sub
End If
End Sub
Upvotes: 1
Reputation: 416121
will close the form immediately without returning to the caller method if there's any.
There's ALWAYS a caller method, even if that method is just the Windows event loop/message pump. If there's no caller method, then the program quits. That's how stack-based programming environments that define pretty much all modern computer systems work: methods are pushed onto the call stack when called, popped when they end, and when there's nothing left on the stack the program is done.
Even within your code for your program or form, what you're asking for is the same as bypassing the caller's entry on the stack, which is equivalent (or worse) to using GOTO, as it breaks the foundational rules of structured programming.
If you really want the program to quit, you can try Environment.Exit()
. Otherwise, Exit Sub
or Return
is your best option.
Upvotes: 1
Reputation: 906
I think the Close()
and Exit Sub
approach is as simple as you could hope for, really :)
Close() won't terminate the current procedure in VB.Net WinForms, by design. So I think the Exit Sub
approach you mentioned is the cleanest way. Close()
's behavior is a little odd, but it allows for scenarios where cleanup code can continue to run, but with the knowledge the form will close when the subroutine has finished.
Upvotes: 0