当主线程不断在另一个串行端口上接收并更新Winform时,如何通过后台线程上的串行端口接收数据?

时间:2019-03-20 10:50:00

标签: c# multithreading winforms serial-port

我需要通过USB至UART模块与两个设备进行串行通信,并更新我的winform。第一个运行正常,但是从第二个SerialPort接收时我一定做错了。我已经确保在硬件方面,正在发送和接收数据,但是我认为在第二个SerialPort上接收到数据时不会提示我的程序。任何帮助表示赞赏。

其工作方式是这样的:启动后,程序开始连续从serialPort1接收数据,并保持实时更新用户界面。仅当按下LStart按钮时才使用第二个串行端口(请参阅代码体内指示的第二个线程代码)。此时,该程序应该发送预定义的字符串并接收响应。问题在于,即使USB-UART模块确认接收到任何信息,该程序也不会被任何响应提示。 附言我不是来自软件领域,也不是具有C#方面的丰富经验,因此请期待可能有些愚蠢的事情。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using System.IO.Ports;
    using System.Threading;
    using System.Globalization;


    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
    public Form1()
    {
        InitializeComponent();
        if (!serialPort1.IsOpen)

            serialPort1.Open();



        if (!serialPort2.IsOpen)                   
        {
            serialPort2.Open();
            richTextBox1.Text = "Port Opened";
        }                                          
    }

    private void Start_Click(object sender, EventArgs e)
    {
        if (!serialPort1.IsOpen)

            serialPort1.Open();

    }





    private void Read_Click(object sender, EventArgs e)
    {

    }


    private string serialRx = string.Empty;
    private void serialPort1_DataReceived(object sender, 
    SerialDataReceivedEventArgs e)
    {
        serialRx += serialPort1.ReadExisting();                                              
    // Add new data to what we have
        string[] lines = serialRx.Split(new char[] { '$' }, 
    StringSplitOptions.None);        // Each line starts with a $ so, split 
    @ $

        for (int i = 0; i < lines.Length - 1; i++)                                          
    // Not processing the last one yet. It might not be complete yet
        {
            if (lines[i].StartsWith("$ABC"))                                                
    // Checking if its the line we are looking for
            {
                 string[] values = lines[i].Split(new char[] { ',' });                                       
    // Splitting @ "," and after this, do what ever we wanna do with these         
    splitted part(s)

                foreach (var value in values)
                  {

                     Invoke(new Action(() => """dataprocessing1"""

                  }
            }
        }
    }






    **/// <Second Thread Code is below>**

    private void LStart_Click(object sender, EventArgs e)
    {
        var thread = new Thread(StartMeasuring);
        thread.IsBackground = true;
        thread.Start();
        LRFStart.Enabled = false;
    }

    private delegate void DisplayCountDelegate(int i);
    private delegate void EnableButtonDelegate();
    private delegate void ClearBoxDelegate();
    private delegate void WritePort2Delegate();
    private delegate void DisplayReceivedDelegate(string mess);

    private void StartMeasuring()
    {   
        LStart.Invoke(new WritePort2Delegate(WriteonSerial2));     
    }

    private void WriteonSerial2()
    {
        string Actionmeasurement = "ABCDEFDS>";
        serialPort2.Write(Actionmeasurement);
    }

    private void EnableButton()
    {
        LStart.Enabled = true;
    }

    private void ClearBox()
    {
        richTextBox1.Clear();
    }

    private void DisplayReading(string mess)
    {    
        string Reading = mess;
        richTextBox1.AppendText(Reading);
        richTextBox1.Invoke(new ClearBoxDelegate(ClearBox));
        LStart.Invoke(new EnableButtonDelegate(EnableButton));
        Reading = string.Empty;
    }

    private string receivedThisTime = string.Empty;
    private void serialPort2_DataReceived(object sender, 
    SerialDataReceivedEventArgs e)
    {
     receivedThisTime += serialPort2.ReadExisting();
     richTextBox1.Invoke(new DisplayReceivedDelegate(DisplayReading), 
        receivedThisTime);   
       }   
     }
    }

1 个答案:

答案 0 :(得分:0)

好吧,我从未同时使用2个串行端口。但我认为您需要获取有关Threads的一些信息。

您必须创建2个线程(serialPort1 1个线程,serialPort2 1个线程)。

您不能只使用一个thread

关于Threads的内容:Thread.Class

Example of Running 2 Threads at the same time