简体   繁体   中英

data_received event runs on which thread?

I'm using a WPF application for serial communication where serial port is created by taking specifications from the user in the mainwindow(GUI) and the port is sent to a background worker as an argument. My question is that I have a datareceived event for the port in my mainwindow thread which I use to read sample data from serial port and do the continuous reading in the BG thread. When using the port that I sent as argument to the BG worker should I define a new datareceived event or will the same one work?

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

Question from title:

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

Second question:
No, you dont have to attach another event handler. This is all the same single SerialPort object, both here and there. Once you have attached an event handler to it, the handler will stay, regardless what you do with the object. You may pass it via args, store in in property, etc. Once +='ed to a SerialPort object, the handler will stay until you explicitely unbind it via -= form that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM