【问题标题】:data_received event runs on which thread?data_received 事件在哪个线程上运行?
【发布时间】:2012-08-08 23:12:46
【问题描述】:

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

【问题讨论】:

    标签: c# wpf serial-port backgroundworker


    【解决方案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 对象,处理程序将一直存在,直到您通过 -= 形式显式取消绑定它。

    【讨论】:

    • @quetz...感谢您的回复,是的,我能够使用相同的事件处理程序来执行我的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 2014-08-13
    • 2021-03-11
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多