从Arduino设备读取串行数据时,WPF应用程序崩溃

时间:2013-07-16 05:54:07

标签: c# wpf serial-port arduino

我有一块Arduino板,通过Xbee模块将一些传感器读数无线传输到串行USB模块。 我编写了以下代码来读取该数据:

    public partial class Debugger : Page
{
    public static string comportnum;
    public delegate void NoArgDelegate();
    public static SerialPort serialX;
    public Debugger()
    {
        InitializeComponent();
        comportnum = "";
    }

    private void ActualButton_Click(object sender, RoutedEventArgs e)
    {
        comportnum = "COM" + comport.Text;

        serialX = new SerialPort(comportnum);
        serialX.BaudRate = 9600;
        try
        {
            serialX.Open();

            serialX.DataReceived += new SerialDataReceivedEventHandler(serialX_DataReceived);
        }
        catch (Exception)
        {
            MessageBox.Show("Houston, we have a problem.");
            //throw;
        }
    }

    void serialX_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        MessageBox.Show("Ping");           
        readingStuff();

    }
    void readingStuff()
    {

        String comdata;
        base.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (NoArgDelegate)delegate
        {
            DebugWindow.Text += "Data";
            comdata = serialX.ReadLine();
            DebugWindow.Text += "\n" + comdata + "\n";
        });
    }

}

只要我有MessageBox.Show(“Ping”),这就有效。没有它,应用程序冻结/崩溃。当它冻结/崩溃时,没有运行时错误。即使在调试时,Visual Studio仍在继续运行,但是我无法单击WPF应用程序的任何其他按钮,甚至无法单击WPF应用程序上的关闭按钮。

我需要找到一种方法来确保数据在没有任何中断的情况下顺利读取,而无需使用MessageBox。

1 个答案:

答案 0 :(得分:2)

只是一个猜测,但尝试修改你的读取方法:

void readingStuff()
{
    String comdata = serialX.ReadLine();
    Dispatcher.Invoke((Action)(() => DebugWindow.Text += "Data\n" + comdata + "\n" ));
}

这将异步读取数据(在调用Dispatcher之前)并使用Invoke而不是BeginInvoke同时确保在读取下一个数据块之前更新UI完成(假设{{ 1}}不是同时调用的。)