vb.net 标签文本不一一更新 Visual Basic

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13828173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:32:11  来源:igfitidea点击:

Label text not updating one by one Visual Basic

vb.netlabel

提问by DemCodeLines

I have this custom class

我有这个自定义类

Public Class labelScroll
    Inherits Label

    Public Shadows Property Text As String
        Get
            Return MyBase.Text
        End Get
        Set(ByVal value As String)
            Dim add As String = ""
            Dim result As String()
            Dim i As Integer
            result = Split(value, vbLf)
            Dim n As Integer = 30
            If (result.Length < n) Then
                n = result.Length
            End If
            Dim start As Integer = result.Length - n
            For i = start To result.Length - 1 Step 1
                add += result(i) + Environment.NewLine
            Next
            MyBase.Text = add
        End Set
    End Property
End Class

I have a form that I placed this labelScroll on and also placed a button: I have this code for the button's click event:

我有一个表单,我在上面放置了这个 labelScroll 并放置了一个按钮:我有这个按钮点击事件的代码:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    LabelScroll1.Text = "1"
    Threading.Thread.Sleep(1000)
    LabelScroll1.Text += "2"
    Threading.Thread.Sleep(1000)
    LabelScroll1.Text += "3"
End Sub

What happens when I click the button is that it takes 2 seconds and then just shows "1" "2" "3" on three lines. What actually should happen is that when the user clicks the button, "1" appears and then Threading.Thread.Sleep(1000)is executed so the program waits for 1 second then prints "2" on the next line.

当我单击按钮时会发生什么,它需要 2 秒钟,然后只在三行上显示“1”“2”“3”。实际应该发生的是,当用户单击按钮时,会出现“1”然后Threading.Thread.Sleep(1000)执行,因此程序等待 1 秒,然后在下一行打印“2”。

Why isn't this happening?

为什么这不发生?

回答by Will A

Setting the text on a label invalidates the control - meaning it will redraw the next time the event queue is processed (effectively). This won't happen whilst you're sleeping on the UI thread - try adding MyBase.Update()immediately after the MyBase.Text = ... line to force an immediate update.

在标签上设置文本会使控件无效 - 这意味着它将在下次处理事件队列时(有效)重绘。当您在 UI 线程上睡觉时,这不会发生 - 尝试MyBase.Update()在 MyBase.Text = ... 行后立即添加以强制立即更新。