1

我正在使用 WPF 应用程序进行串行通信,其中通过在主窗口(GUI)中获取用户的规范来创建串行端口,并将端口作为参数发送到后台工作人员。我的问题是我的主窗口线程中有一个端口的 datareceived 事件,用于从串行端口读取样本数据并在 BG 线程中进行连续读取。当使用我作为参数发送给 BG 工作人员的端口时,我应该定义一个新的 datareceived 事件还是同样的一个工作?

private void SerialThread_DoWork(object Sender, DoWorkEventArgs e )
    {

        BGargs args = e.Argument as BGargs;
        SerialPort BGport = args.PORT;
        string MODE = args.MODE;
        string filePath = args.filepath;
        BGport.DataReceived +=new SerialDataReceivedEventHandler(BGport_DataReceived);
        Dispatcher.BeginInvoke((Action)delegate() { run_button.IsEnabled = false; });
        switch (MODE)
        {
            case "EXT_trigger":
                while (SerialThread.CancellationPending)
                {
                    FileStream file = new FileStream(filePath, FileMode.Append, FileAccess.Write);
                    using (StreamWriter Writer = new StreamWriter(file))
                    {
                        //code to continuously trigger and read data and then write to file
                    }
                }

                    break;
        }
    }
4

1 回答 1

1

来自标题的问题:

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

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

第二个问题:
不,您不必附加另一个事件处理程序。这里和那里都是同一个 SerialPort 对象。一旦您将事件处理程序附加到它,处理程序将保留,无论您对对象做什么。您可以通过 args 传递它,存储在属性中,等等。一旦 +='ed 到 SerialPort 对象,处理程序将一直存在,直到您通过 -= 明确取消绑定它形成该对象。

于 2012-08-08T23:15:24.930 回答