InvokeRequired keeps returning false when true is expected

谁说我不能喝 提交于 2020-01-15 06:18:32

问题


I have the following test code. It does nothing useful, but it's there for me to understand VB:

Imports System
Imports System.IO
Imports System.Diagnostics
Imports Microsoft.VisualBasic
Imports System.Threading

Public Class Sandbox
    Public Shared num As NumericUpDown

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim objWrk As Worker
        objWrk = New Worker
        objWrk.Show()
    End Sub
End Class

Public Class Worker
    Public Sub Show()
        Dim runThread As New System.Threading.Thread(AddressOf Run)      ' Call the runner in a seperate thread
        runThread.Start()
    End Sub

    Public Sub Run()
        runToggle(1000)
    End Sub

    Public Delegate Sub runToggleInvoker(ByVal value As Integer)
    Public Sub runToggle(ByVal value As Integer)
        If Sandbox.Label1.InvokeRequired = True Then
            Sandbox.Label1.Invoke(New runToggleInvoker(AddressOf runToggle), value)
        Else
            Sandbox.Label1.Text = value
        End If
    End Sub
End Class

The form consists of a Button and a Label.

Just for learning purposes I've put the method to change the text in the label in another thread. However the InvokeRequired value keeps returning False. How is this possible? The Label1is created in the main thread, and it is being adjusted in the runThread hence InvokeRequired should give True.

Here I read that this happens when the handle for the form is not created yet so I changed my Run method:

Public Sub Run()
            Sandbox.Show()
            runToggle(1000)
        End Sub

This does not solve the problem.


回答1:


According to Control.InvokeRequired Property

If the control's handle does not yet exist, InvokeRequired searches up the control's parent chain until it finds a control or form that does have a window handle. If no appropriate handle can be found, the InvokeRequired method returns false.



来源:https://stackoverflow.com/questions/10733693/invokerequired-keeps-returning-false-when-true-is-expected

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