Threading, Delegates and the Invoke method.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sebouh
    New Member
    • Feb 2007
    • 77

    Threading, Delegates and the Invoke method.

    Hi guys. I was messing with Threading and stuff, and i have reached a point where i'm not sure what's causing the current behavior.

    Here's the code:
    Code:
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim nt As New newThread(Me)
            Dim t As New Threading.Thread(AddressOf nt.ThreadCode)
            t.Start()
        End Sub
    
        Public Sub CreateMessageBox()
            Dim f As New Form()
            f.Show()
        End Sub
    End Class
    
    
    Public Class newThread
    
        Public Delegate Sub Inform()
        Public sendInform As Inform
        Public main As Form
    
        Public Sub New(ByRef main As Form1)
            Me.main = main
            sendInform = New Inform(AddressOf main.CreateMessageBox)
        End Sub
    
        Public Sub ThreadCode()
           Threading.Thread.Sleep(2000)
        '*********************************************
           sendInform() (VS) main.Invoke(sendInform)
        '***********************************
        End Sub
    End Class
    The problem is in the last statement, when i use main.Invoke() the CreatemessageBo x creates a msgbx, which is part of the Form1. But when i use sendInform() I get a messagebx that appears, but is part of the new thread. So if it were a Form instead of a msgbx, it would appear and then close as soon as the new thread exits.

    My questionis , obviously, why? Why is one working the way i want it to and the other not.

    My theory is that, when the main.invoke() is used, the loader(?) already assigns the address of the method as the main thread's Createmsgbx. But so when i use invoke(), it is somehow assigning the new thread's createmsgbx address. But i have a feeling i'm wrong, cause i know that threads share code, so the addresses must be the same. So why i one getting "assigned" as a call from the main thread, and the other as a method call from the new thread?

    Thanks a lot.
Working...