开发者

working with threads and serial ports and DB calls

I'm attempting to read data from a serial port, show the data in some control, and insert the data in to a DB.

I've got it inserting into a DB and it's reading correctly, however, it is not writing to the textbox anymore since I added the DB changes. How can I accomplish these three tasks simultaneously. The following is some of my code.

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开发者_Python百科();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            connection.Close();
            connection.Dispose();
        }

    }

Thank you in advance.


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

You execute code with a side effects on the Dispatcher thread - reading from the serial port on the Dispatcher/UI thread is probably not healthy - instead what you probably meant to do is use the string variable as a closure and display its content:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜