【问题标题】:VB.Net - How to use Nested-if in Timer every 1000 microsecond?VB.Net - 如何每 1000 微秒在 Timer 中使用 Nested-if?
【发布时间】:2019-09-13 05:37:02
【问题描述】:

我想执行 couatall.text 来递增,但如果在每 1000 微秒/1 秒的计时器中进行嵌套,则它不起作用。请帮我, 这是我的代码...

我这样做是因为我的传感器一次读取的值是小于 900 的值的 2、3 倍或更多,也就是说,如果我只使用“1-If 条件”,它会计数 2、3 倍或更多。所以我的逻辑(菜鸟)是如果我的传感器读数小于 900,然后如果我的传感器读数大于 899,它会执行“coutall.Text = coutall.Text + 1”代码来计数 1,依此类推。

Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
    Try
        Dim i As Single = SerialPort1.ReadExisting 'get data of my sensor
        label1.Text = i.ToString                   'display on label1.text
        If label1.Text < 900 Then
            'messageBox.show("working here")
            'I really make it comment lines don't mind it.
            If label1.Text > 899 Then   'not working when my i is <  to 900
                coutall.Text = coutall.Text + 1
            End If
        Else
            'nothing
        End If
    Catch ex As Exception

    End Try
End Sub

如果我的解释不清楚,请告诉我,对不起,我的英语不好。 :)

【问题讨论】:

  • 永远不会到达递增行。当数据小于 900 时,第一个 If 将为真,但这意味着第二个 If 永远不会为真。所以你永远不会到达递增线。除此之外,不清楚你打算用这段代码做什么。
  • 啊哈!我明白你的意思了,谢谢!那么我使用的方法不是嵌套if? while循环,for循环还是什么?呵呵,对不起,我是新手。
  • 另外,不要使用 UI 控件(如标签)而不是变量 - UI 控件会非常慢。所以它应该是If i &lt; 900 等等。另一件事:如果你使用Option Strict On,它将确保变量类型正确匹配,并且不会因为它必须猜测的类型转换而减速。
  • 谢谢安德鲁先生,这里怎么表扬?呵呵
  • @MarkL 为什么我不能是 899.9?当然小于 900 但也大于 899。我们这里不处理整数。我被声明为单身。

标签: vb.net timer nested-if


【解决方案1】:

这是答案,仅供将来使用(如果)

Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
    Try
        Dim i As Single = SerialPort1.ReadExisting
        label1.Text = i.ToString
        If label1.Text < 900 Then
            Timer1.Enabled = True 'instead using nested here create timer again
        End If
    Catch ex As Exception

    End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 'new timer
    If label1.Text > 899 Then 'looks like nested
        coutall.Text = coutall.Text + 1 'execute count + 1
        Timer1.Enabled = False 'then shutdown timer 1
    End If
End Sub

【讨论】:

  • 您仍然有一个空的 Catch,因此您的代码只会吞下错误并继续处理未发现的错误。您还没有打开 Option Strict,这会使您的代码容易受到运行时错误的影响,这些错误应该在编译时发现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 2022-10-19
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
相关资源
最近更新 更多