当期望为true时,InvokeRequired不断返回false [英] InvokeRequired keeps returning false when true is expected

查看:401
本文介绍了当期望为true时,InvokeRequired不断返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下测试代码.它没有任何用处,但对我来说,了解VB即可:

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

该表单由ButtonLabel组成.

出于学习目的,我将方法更改为另一个线程中标签中的文本.但是,InvokeRequired值一直返回False.这怎么可能? Label1是在主线程中创建的,并且正在runThread中对其进行调整,因此InvokeRequired应该为True.

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.

在这里我读到这个当尚未创建表单的句柄时发生,因此我更改了Run方法:

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

这不能解决问题.

推荐答案

需要如果控件的句柄尚不存在,InvokeRequired将在控件的父链中搜索,直到找到具有窗口句柄的控件或窗体.如果找不到合适的句柄,则InvokeRequired方法将返回 false .

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.

这篇关于当期望为true时,InvokeRequired不断返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆