使用串行通信时,用户界面很滞后

时间:2016-06-07 05:52:54

标签: vb.net datagridview serial-port

美好的一天! 我想从串口读取数据。可以每2秒读取一次数据并将其保存到数据库中,幸运的是,它已经完成了。我使用datagridview来显示和保存它。但似乎非常迟钝。我必须等几秒钟才能点击另一个按钮。 还有其他方法可以做到这一点吗? 任何帮助都可以。谢谢!

Imports System.Data.OleDb
Public Class PICtoVB[enter image description here][1]
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Recto D Sanchez Jr\Desktop\Datalogger GUI\test\test\bin\Debug\database1.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim timerval As Integer = 0

Private Sub btnconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnconnect.Click
    btnconnect.Enabled = False
    btnread.Enabled = True
    btndisconnect.Enabled = True
    SerialPort1.Open()
    Timer1.Enabled = True
End Sub

Private Sub btndisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndisconnect.Click
    btndisconnect.Enabled = False
    btnread.Enabled = False
    btnconnect.Enabled = True
    Timer1.Enabled = False
    SerialPort1.Close()
End Sub


Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    timerval = timerval + 1

    Dim serialdata1 As String
    Dim serialdata2 As String
    Dim serialdata3 As String
    Dim serialdata4 As String

    Try
        serialdata1 = SerialPort1.ReadLine.ToString
        serialdata2 = SerialPort1.ReadLine.ToString
        serialdata3 = SerialPort1.ReadLine.ToString
        serialdata4 = SerialPort1.ReadLine.ToString
        dgvdata.Rows.Add(serialdata1, serialdata2, serialdata3, serialdata4)
        DATALOGBindingSource1.AddNew()
        DATETextBox.Text = serialdata1
        TIMETextBox.Text = serialdata2
        TEMP__C_TextBox.Text = serialdata3
        RH____TextBox.Text = serialdata4
        DATALOGBindingSource1.EndEdit()
        DATALOGTableAdapter1.Update(Database1DataSet1.DATALOG)

    Catch ex As Exception

    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

您正在从UI线程上的SerialPort读取数据,这意味着它太忙而无法维护UI,因此UI会冻结一段时间。一般来说,您处理DataReceived的{​​{1}}事件并在那里读取数据。该事件处理程序在辅助线程上执行,这意味着您可以根据需要读取和操作数据,而不会影响UI。但是,您无法从那里更新UI,因此,一旦处理完数据并准备好显示它,就需要编组对UI线程的方法调用并在那里进行更新。这是一个你可以找到很多例子的话题。