data_received事件在哪个线程上运行?

时间:2012-08-08 23:12:47

标签: c# wpf serial-port backgroundworker

我正在使用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;
        }
    }

1 个答案:

答案 0 :(得分: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对象,处理程序将保持不变,直到你通过 - =形成该对象明确解除绑定。