VB.NET Invoke cannot be called on a control until the window handle has been created, BUT the handle is created

妖精的绣舞 提交于 2019-12-06 01:54:33

The instance of My.Forms.Form1 aka. Form1 will be different in each thread. You need a handle to the correct instance. Drop a button onto your Form1 and add the following code:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Threading.Tasks.Task.Factory.StartNew(Sub() Class1.Wrong())
        Threading.Tasks.Task.Factory.StartNew(Sub() Class1.Correct(Me))
    End Sub

End Class

Public Class Class1

    Public Shared Sub Wrong()
        Debug.WriteLine(String.Format("(Other thread, wrong) InvokeRequired={0}, IsHandleCreated={1}", Form1.InvokeRequired, Form1.IsHandleCreated))
    End Sub

    Public Shared Sub Correct(instance As Form1)
        Debug.WriteLine(String.Format("(Other thread, correct) InvokeRequired={0}, IsHandleCreated={1}", instance.InvokeRequired, instance.IsHandleCreated))
    End Sub

End Class

Output

(Other thread, correct) InvokeRequired=True, IsHandleCreated=True

(Other thread, wrong) InvokeRequired=False, IsHandleCreated=False

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!