简体   繁体   中英

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();
            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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM