簡體   English   中英

使用線程和串行端口以及數據庫調用

[英]working with threads and serial ports and DB calls

我正在嘗試從串行端口讀取數據,在某些控件中顯示數據,然后將數據插入數據庫。

我已經將它插入數據庫並且它可以正確讀取,但是,自從我添加了數據庫更改以來,它不再寫入文本框。 我怎樣才能同時完成這三個任務。 以下是我的一些代碼。

void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string force = "";
        force = serialPort1.ReadExisting().Split('.')[0].ToString();

        Invoke(new Action(() => richTextBox1.AppendText(serialPort1.ReadExisting())));


        string queryString = "Insert into Table....";


        OdbcConnection connection = new OdbcConnection();
        connection.ConnectionString = Settings.Default.STIMConnection;
        OdbcCommand command = new OdbcCommand(queryString, connection);

        command.CommandType = CommandType.Text;
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            connection.Close();
            connection.Dispose();
        }

    }

先感謝您。

Invoke(new Action(() => richTextBox1.AppendText(serialPort1.ReadExisting())));

您在 Dispatcher 線程上執行帶有副作用的代碼 - 從 Dispatcher/UI 線程上的串行端口讀取可能不健康 - 相反,您可能打算使用字符串變量作為閉包並顯示其內容:

Invoke(new Action(() => richTextBox1.AppendText(force)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM