[英]Multithreading help in VB.NET
基本上每隔2秒,我就使用串行连接通过设备获得2位十进制数字的值,因此我已将每个字节转换为字符,然后连接为通过串行端口接收的第二个字符(字节),然后依次分配给一个文本框4(MB, GC,INS,OU),那么每次在MB和OU文本框中(而不是其他文本框中)更新值时,会发生什么情况。 因此,如果有人可以通过这些逻辑帮助我。 (是vb的新手,因此请尽可能地详尽)。
码:
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
cc = Chr(SerialPort1.ReadByte())
dd = Chr(SerialPort1.ReadByte())
ee = cc + dd
ReceivedText(ee)
End Sub
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If c = 0 Then
If Me.MB.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.MB.Text = [text] 'append text
End If
c = 1
ElseIf c = 1 Then
If Me.GC.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.GC.Text = [text] 'append text
End If
c = 2
ElseIf c = 2 Then
If Me.OU.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.OU.Text = [text] 'append text
End If
c = 3
ElseIf c = 3 Then
If Me.INS.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.INS.Text = [text] 'append text
c = 0
End If
End If
End Sub
如果要设置断点,则会注意到每个调用C被修改了两次。 一个用于“正常”调用,另一个用于调用。 我建议您改变设置“ c”的逻辑。 更改文本框值后将其放置在右边。
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If c = 0 Then
If Me.MB.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.MB.Text = [text] 'append text
c = 1
End If
ElseIf c = 1 Then
If Me.GC.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.GC.Text = [text] 'append text
c = 2
End If
ElseIf c = 2 Then
If Me.OU.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.OU.Text = [text] 'append text
c = 3
End If
ElseIf c = 3 Then
If Me.INS.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.INS.Text = [text] 'append text
c = 0
End If
End If
End Sub
我还建议您放置更多的meaninfull变量名称。 使用c,cc,ee之类的东西没有多大意义。
您也可以减少一些代码。 尽量不要重复自己。 (注意:我没有进行编译以查看它是否有效)。
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
Dim tbToUpdate As TextBox
' This could even be in an array
Select Case c
Case 0
tbToUpdate = Me.MB
Case 1
tbToUpdate = Me.GC
Case 2
tbToUpdate = Me.OU
Case 3
tbToUpdate = Me.INS
End Case
If tbToUpdate.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
tbToUpdate.Text = [text] 'append text
c += 1
If c == 4 Then
c = 0
End If
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.