在WPF GUI类中处理串行线程事件 [英] Handle serial thread event in WPF GUI class

查看:145
本文介绍了在WPF GUI类中处理串行线程事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个串行端口类,我想通过我的GUI控制发送/接收,并让GUI根据从串行端口接收到的数据(或其他事件)进行更新。因此,两个相关的类是串行类和主窗口类。

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.

我有下面的代码可以编译,但是尝试运行时会出现异常。 / p>

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

然后在我的GUI类中……

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?

推荐答案

不创建实例就无法访问myPort。

You can't access myPort without creating an instance.

MySerThread myPort = new MySerThread();

这篇关于在WPF GUI类中处理串行线程事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆