vb.net 多线程 [英] vb.net multi threading

查看:23
本文介绍了vb.net 多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为系统编写一些代码,需要在 VB.NET 中使用线程而不是普通计时器.

I have been doing some coding for a system and need to use threading instead of normal timers in VB.NET.

它工作正常,但问题在于闪烁时间,当单击按钮时,它会按预期闪烁,如果在测试中单击它不止一次,则闪烁时间大致乘以原始睡眠线程时间(750 毫秒),每次点击都会继续发生这种情况.

It works fine but the problem lies in the blink timings, when the button is clicked then it blinks as expected, if in testing it is clicked more than once then the blinking time roughly multiplies by the original sleep thread time (750ms), this continues to happen for every click.

我该怎么做才能使眨眼不加速?下面是代码!

What can I do to make the blink not speed up? Below is the code!

    Private _flash As Boolean = False

    Private Sub btnButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnButton1.Click
        _flash = True
        Dim FlashThread As New Thread(New ThreadStart(AddressOf FlashLabel))
        FlashThread.Start()

    End Sub

    Private Sub FlashLabel()

        Dim _color As Color = Color.Gray    

        While _flash

              If label1.ForeColor.Equals(_color) Then
                    label1.ForeColor = Color.Red
              Else
                    label1.ForeColor = Color.Gray

              System.Threading.Thread.Sleep(750)

        End While
    End Sub

推荐答案

每次点击按钮,都会启动一个新线程,所以如果点击两次按钮,就会启动两个线程,两者都在切换颜色以 750 毫秒为间隔,因此看起来好像有一个线程以两倍的速度执行此操作.如果 _flash 标志已经设置,一个简单的方法是简单地跳过启动新线程,例如:

Every time the button is clicked, you are starting a new thread, so if you click the button twice, it will start two threads, both of which are toggling the colors at 750 millisecond intervals, so it appears as if there was one thread doing it twice as fast. A simple way around this is to simply skip starting the new thread if the _flash flag is already set, for instance:

Private Sub btnButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnButton1.Click
    If Not _flash Then
        _flash = True
        Dim FlashThread As New Thread(New ThreadStart(AddressOf FlashLabel))
        FlashThread.Start()
    End If
End Sub

这篇关于vb.net 多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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