简体   繁体   中英

How can I use a .NET EventHandler to return a parameter into a specific variable?

I am using the SerialDataReceivedEventHandler of the SerialPort class for communicating with a serial port device. I send a SCPI code to the device by SerialPortObject.Write(command) where command is a string type. Then the device will reply with a string that is collected by the event handler and is read into a variable by SerialPortObject.ReadLine() .

I send different commands to the serial port eg to acquire the speed or position of a stepper motor and want to store them in string speed or string position respectively. However, the event handler can only read the line sent by the device without knowing which variable it should store the data in. A solution is to type the SerialPortObject.ReadLine() command after each SerialPortObject.Write() command, however, this pauses the thread and the Windows From halts until the device responds which sometimes might be long, while the event handler will do this asynchronously.

string position, speed;
SerialPortObject.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        var input = SerialPortObject.ReadLine();
    }
public void CurrentPosition()
    {
        //This requests for the current position (command is specific to the device)
        SerialPortObject.Write("?X");
    }
public void Speed()
    {
        //This requests for the current position (command is specific to the device)
        SerialPortObject.Write("?V");
    }

My question How can I have the SerialDataReceivedEventHandler to recognize which of the CurrentPosition() or Speed() raised the event and put the device response into the position and speed respectively.

I think you should keep state of which command was last send eg with an enum. Or the sending side should add (if posible) the parameter which was requested.

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