在一个时间增量上更改标签

时间:2012-04-11 20:51:39

标签: vb.net label thread-sleep

我正在尝试制作一个每秒更改一次事件的标签。我现在拥有的东西让线程一直从“摇滚”到“射击”,并跳过“纸”和“剪刀”。有没有人有任何想法,我应该做什么来正确显示标签,以便它们都以相等的时间增量显示?任何帮助将不胜感激。

lblCountdown.Text = "Rock"
System.Threading.Thread.Sleep(1000)
lblCountdown.Text = "Paper"
System.Threading.Thread.Sleep(1000)
lblCountdown.Text = "Scissors"
System.Threading.Thread.Sleep(1000)
lblCountdown.Text = "Shoot!"

2 个答案:

答案 0 :(得分:1)

如果您从UI线程调用它,渲染将锁定,直到代码完成,因此您不会看到Paper或Scissors。一个解决方案(不是最佳解决方案,但 解决方案)是在每个Me.Refresh()之前调用Application.DoEvents()Sleep。这将告诉用户界面重绘自己。

更好的解决方案是使用某种计时器,该计时器以1秒的间隔打开,这将在另一个线程中运行,从而释放UI线程以获取更重要的事情。

答案 1 :(得分:0)

定时器和调用是处理这个问题的好方法:

Private WithEvents m_tmrGame As New System.Timers.Timer(1000)
Private m_intShouldBeAnEnum As Integer = 1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    m_tmrGame.Start()

End Sub

Private Sub m_tmrGame_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_tmrGame.Elapsed

    Dim strCurrentObject As String = String.Empty

    Select Case m_intShouldBeAnEnum
        Case 1
            strCurrentObject = "Rock"
            m_intShouldBeAnEnum = 2
        Case 2
            strCurrentObject = "Paper"
            m_intShouldBeAnEnum = 3
        Case 3
            strCurrentObject = "Scissors"
            m_intShouldBeAnEnum = 4
        Case 4
            strCurrentObject = "Shoot!"
            m_intShouldBeAnEnum = 1
            m_tmrGame.Stop()
    End Select

    lblCountdown.Invoke(Sub(lblTarget As Label) lblTarget.Text = strCurrentObject, New Object() {lblCountdown})

End Sub