title: Infinite Loop and Cross Threading
body: <p>I am a student attempting to learn VB.NET on my own. Today I wanted to tackle the BackgroundWorker component. I found an excellent article online: <a href="http://www.dreamincode.net/forums/topic/88605-the-background-worker/%22How%20To%20Use%20a%20Background%20Worker%22" rel="nofollow">How To Use a Background Worker</a>. I successfully completed the walkthrough and even performed the "adventorous" part that dealt with working with controls updating across threads using delegates.</p>
  
  <p>Now I came to a part that I didn't understand how it was working. To summarize the following code, I have a delegate that has a Label and a String in its signature. I then have a subroutine that is called on the worker thread. Inside this subroutine the delegate is created and (I guess) ran again so that it is on the same (Main) thread. Please correct me if I'm wrong here.</p>
  
  <p>Here is the method is performed on the worker thread:</p>
  
  <pre><code>    Private Sub My_BgWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles My_BGWorker.DoWork
  
          SetLabelText_ThreadSafe(Me.lbl_Status, FormatPercent(i / m_CountTo, 2))
  
  End Sub
  </code></pre>
  
  <p>I've only included the line of code that is of importance to this question. As you can see this then calls a subroutine that I mentioned:</p>
  
  <pre><code>    Private Sub SetLabelText_ThreadSafe(ByVal lbl As Label, ByVal txt As String)
      ' InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
      ' If these threads are different, it returns true.
      If lbl.InvokeRequired Then
          'WORKS: Dim MyDelegate As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
          'WORKS: Me.Invoke(MyDelegate, New Object() {lbl, txt})
          MyDel.Invoke(lbl, txt)
      Else
          lbl.Text = txt
      End If
  End Sub
  </code></pre>
  
  <p>Now as you can see I have the code commented out 'WORKS' because it does, but I'm confused as why it goes into an infinite loop when the <code>MyDel.Invoke(lbl, txt)</code> is called because the delegate is created in the Main form Declarations.</p>
  
  <p>Thank you.</p>
  
  <p>EDIT: And for clarification, the delegate in the Main form Declaractions is: </p>
  
  <pre><code>Dim MyDel As New SetLabelText_Delegate(AddressOf SetLabelText_ThreadSafe)
  </code></pre>