串行监视器、DataReceived 处理程序误解 C#、WPF

Serial monitor, DataReceived handler misunderstanding C#, WPF

我正在为我的 WPF 应用程序开发串行监视器,使用 C# 编程。 我在管理 DataReceived 事件时遇到了麻烦,因为我想要一个实时监视器,例如 HyperTerminal 或 TeraTerm(我没有使用它们,因为我希望我的终端成为以太网通信工具的一部分,我已经使用 winPcap 开发了它) .

我必须从我的微控制器读取一些数据,将其显示在文本框上(它只打印一个菜单和可用命令列表)并且当它完成加载序列时我想与之交互,没什么特别的, 只需要发送一个"flash-"命令来烧写板子的fpga

当我尝试用收到的数据更新 textbox.text 时,我的应用程序出现异常。我试图到处搜索,但尽管有很多示例,但我没有找到正确解释代码的内容。

这是代码,在此先感谢

namespace WpfApplication1 {
/// <summary>
/// Interaction logic for SerialMonitor.xaml
/// </summary>
public partial class SerialMonitor : Window {

    //VARIABLES
    public SerialPort comPort = new SerialPort();

    public SerialMonitor() {
        //initialization
        InitializeComponent();
        scanPorts();

    }



    private void scanPorts() {
        textBoxIndata.Clear();
        string[] ports = SerialPort.GetPortNames();
        foreach (string port in ports) {
            comboBoxPorts.Items.Add(port);
        }
    }



    private void openComBtn_Click(object sender , RoutedEventArgs e) {

        comPort.Parity = Parity.None;
        comPort.DataBits = 8;
        comPort.ReadTimeout = 500;
        comPort.StopBits = StopBits.One;

        if (comboBoxPorts.SelectedItem != null && comboBoxPorts.SelectedItem != null) {

            comPort.PortName = comboBoxPorts.SelectedItem.ToString();
            comPort.BaudRate = Convert.ToInt32(comboBoxBaud.Text);

            try {
                //Open port and add the event handler on datareceived
                comPort.Open();                 
                comPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString());                    
            }              
        }
        if (comPort.IsOpen) {
            label1.Content = "COM PORT OPEN";              
        }
    }


    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {

    }


    //function to update the textBox, didn't manage to get it working
    private void updateUI (string s) {

    }



    //CLOSE AND EXIT BUTTONS
    private void closeComBtn_Click(object sender , RoutedEventArgs e) {
        if (comPort.IsOpen) {
            comPort.Close();
            label1.Content = "COM PORT CLOSED";
        }
    }

    private void exitBtn_Click(object sender , RoutedEventArgs e) {
        if (comPort.IsOpen) {
            comPort.Close();
        }
        this.Close();
    }
}

}

我现在遇到的问题是,当我使用 SerialPort.Write(string cmd) 发送命令时,我无法读回答案...

编辑:修复了所有问题,如果有人对编写这样的工具感兴趣,我将 post 代码 :)

DataReceived 事件 returns 在 another/secondary 线程上,这意味着您将不得不编组回 UI 线程以更新您的 TextBox

SerialPort.DataReceived Event

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

您可以使用 Dispatcher.BeginInvokeDispatcher.Invoke Method 编组回主线程

例子

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

我现在遇到的问题是,当我使用 SerialPort.Write(string cmd) 发送命令时,我无法读回答案...