Close Form in Thread

usvpn

Freshman
Joined
Apr 19, 2010
Messages
45
Hi,
When I am inside a thread, I cannot simply call Me.Close or I get cross threading error!
So I need to use some code like this and then call SetClose()
Visual Basic:
Private Delegate Sub SetCloseCallback()
Private Sub SetClose()
    If Me.InvokeRequired Then
        Dim d As New SetCloseCallback(AddressOf SetClose)
        Me.Invoke(d, New Object() {Me})
    Else
        Me.Close()
    End If
End Sub
But this don't work for some reason I don't know, anyone can see something wrong with my code? :confused:
Thank you.
 
I was pretty sure I could see what was wrong with your code off the bat, but I wanted to be sure that it explained the behavior you were seeing, so I changed your code to this:
Code:
Public Class Form1
    Private Delegate Sub SetCloseCallback()
    Private Sub SetClose()
        Throw New InvalidOperationException
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Invoke(New SetCloseCallback(AddressOf SetClose), New Object() {})
    End Sub
End Class
When run, this code behaves the same way, i.e. nothing happens. I'm obviously throwing an exception, but it's not being caught. I'm not sure exactly why, but the exception is being swallowed somewhere. My guess is that it is related to the Invoke function. This is a problem though, because when you don't get the exception you can't figure out what's going on.

If you put a breakpoint at the top of the SetClose function you would see that it's never even being called. The issue is with your use of Invoke; you don't need to specify Me in your argument list. (The target, Me, is actually bound when you create the delegate.) An exception is being thrown when the Invoke function tries to call SetClose, because your argument list is wrong, but the exception is being swallowed.

The good news is that you can fix the problem with two keystrokes.
 
Back
Top