vb.netmultithreadingthread-safetyinvokeinvokerequired

When execution reaches Me.Invoke, it hangs


I have simplified my code to a single form, as follows:

Imports System.Threading.Tasks

Public Class frmTest
    Inherits Form

    Public Sub WorkerSub(oAction As action)
        Dim x = 0
        oAction.Invoke()
        x += 1
    End Sub

    Private Sub Test()
        If Me.InvokeRequired Then
            Me.Invoke(Sub()
                          Test()
                      End Sub)
        Else
            MsgBox("Test")
        End If
    End Sub

    Private Sub btnTrigger_Click(sender As Object, e As EventArgs) Handles btnTrigger.Click
        Dim tt As Task = Task.Factory.StartNew(Sub()
                                                   WorkerSub(AddressOf Test)
                                               End Sub)
        tt.Wait()

        ' Never arrives here
        Stop
    End Sub

End Class

When Me.Invoke(sub() ... in Sub Test is executed, it hangs. No error is thrown & nothing written in the Event Viewer.

Even if I press F11, Debug Into, it hangs.

Any Ideas?

Thanks

JP


Solution

  • Found the Problem.

    The main thread is waiting for another thread to finish.

    t.Wait()
    

    The invoke on the main thread needs to wait to, so there's a deadlock.