Handle serial thread event in WPF GUI class

旧时模样 提交于 2019-12-11 13:41:31

问题


I have a serial port class, and I would like to control send/receive via my GUI, and have the GUI update based on receipt of data from the serial port (or other events). So the two relevant classes are the serial class and the main window class.

I have the code below which compiles, but I get an exception when I try to run.

public class MySerThread
{
    public SerialPort serport;
    public event SerialDataReceivedEventHandler newSerData;

    public MySerThread()
    {
        serport = new SerialPort("COM1", 115200);
        serport.Open();
        serport.DataReceived += DataReceivedHandler;
    }

    public void DataReceivedHandler(object s, SerialDataReceivedEventArgs e)
    {
        byte[] data = new byte[serport.BytesToRead];
        serport.Read(data, 0, data.Length);

        // here's where I think I'm going wrong?
        if(newSerData != null)
            newSerData(s,e);
    }
}

And then in my GUI class...

public partial class MainWindow : Window
{
    MySerThread myPort;

    public MainWindow()
    {
        // Exception triggers here
        myPort.newSerData += DisplaySerDataHandler;
    }

    private void DisplaySerDataHandler(object sender, SerialDataReceivedEventArgs e)
    {
        this.ReceivedCallback(e);
    }

    private void ReceivedCallback(SerialDataReceivedEventArgs e)
    {
        if(this.someTextBlock.Dispatcher.CheckAccess())
        {
            this.UpdateTextBlock(e);
        }
        else
        {
            this.someTextBlock.Dispatcher.BeginInvoke(new Action<SerialDataReceivedEventArgs>(this.UpdateTextBlock), e);
        }
    }

    private void UpdateTextBlock(SerialDataReceivedEventArgs e)
    {
        someTextBlock.Text = "got new data";
    }
}

So, what am I doing wrong here? What is the best way to do this?


回答1:


You can't access myPort without creating an instance.

MySerThread myPort = new MySerThread();


来源:https://stackoverflow.com/questions/13849850/handle-serial-thread-event-in-wpf-gui-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!