繁体   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