一个线程试图通过串口将数据传递给另一个线程

本文关键字:线程 数据 串口 另一个 一个 | 更新日期: 2023-09-27 18:15:42

在过去的2天里,我被卡住了,但没有解决方案。

我有一个自己编写的类,它的对象之一是"SerialPort"。net类。
在我的主窗口中,我创建了一个名为"SerialPortComm"的类实例,然后我通过我的一些函数发送命令到串口,并通过"DataReceived"事件接收答案。

但是当我试图使用Dispatcher。BeginInvoke写入我收到的数据(成功),没有显示在我试图写入的RichTextBox上。

是什么导致的,我怎样才能使它起作用?

SerialPortComm.cs (编辑)

public partial class SerialPortComm : UserControl
{
   public SerialPort mySerialPort = new SerialPort();
   public void Open_Port(string comNumber, int baudRate)
   {
      mySerialPort.PortName = comNumber;
      mySerialPort.BaudRate = baudRate;
      mySerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
      mySerialPort.Open();
   }
   public void SetStringDataFromControl(SerialPort sp, string content)
   {
      sp.Write(content + "'n");
   }
   public void SetStringDataFromControl(SerialPort sp, string content)
   {
      sp.Write(content + "'n");
   }
   public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
   {
      SerialPort sp = (SerialPort)sender;
      DataRX = sp.ReadExisting(); // Read the data from the Serial Port
      // Print it on the Log
      RichTextBox_logView.Dispatcher.BeginInvoke((Action)delegate()
      {
          RichTextBox_logView.AppendText(DataRX);
          RichTextBox_logView.ScrollToEnd();
      });
   }
}

Commands.cs

class Commands
{
   public void SetCommand(SerialPortComm sp, string command)
   {
       sp.SetStringDataFromControl(sp.mySerialPort, command); 
   }
}

MainWindow.cs

public partial class MainWindow : Window
{
   Commands cmd = new Commands();
   SerialPortComm sp1 = new SerialPortComm();  
   public MainWindow()
   {
       InitializeComponent();
       sp1.Open_Port("COM6", 115200);
   }
   private async void TextBox_input_KeyDown(object sender, KeyEventArgs e)
   {
       if (e.Key == Key.Enter)
       {
           cmd.SetCommand(sp1, "top");
           cmd.SetCommand(sp1, "run");
           // .... //
       }
   }
}

一个线程试图通过串口将数据传递给另一个线程

我认为你有UI线程阻塞,尝试通过ThreadPool线程调用COM消息:

public void SetCommand(SerialPortComm sp, string command)
{
   Task.Factory.StartNew( () => {
      sp.SetStringDataFromControl(sp.mySerialPort, command); 
 });
}

唯一的问题是这些调用不能保证按顺序运行和完成。您可能需要进行调整,以使调用按顺序排队和使用。通过Concurrent集合命名空间查看生产者/消费者模式。

http://www.nullskull.com/a/1464/producerconsumer -排队-和- blockingcollection - c - 40. aspx

或者,您可以通过在它们自己的专用(单个)线程中调用所有命令来避免并发问题,如下所示:

   if (e.Key == Key.Enter)
   {
     Task.Factory.StartNew( () => {
       cmd.SetCommand(sp1, "top");
       cmd.SetCommand(sp1, "run");
       // .... //
     });
   }