微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 .NET EventHandler 将参数返回到特定变量?

如何解决如何使用 .NET EventHandler 将参数返回到特定变量?

我使用 SerialDataReceivedEventHandler 类的 SerialPort 与串行端口设备进行通信。我通过 SerialPortObject.Write(command) 向设备发送 SCPI 代码,其中 command 是字符串类型。然后设备将回复一个字符串,该字符串由事件处理程序收集并由 SerialPortObject.ReadLine() 读入变量。

我向串行端口发送不同的命令,例如获取步进电机的速度或位置,并希望将它们分别存储在 string speedstring position 中。但是,事件处理程序只能读取设备发送的行而不知道它应该将数据存储在哪个变量中。 解决方案是在每个 SerialPortObject.ReadLine() 命令之后键入 SerialPortObject.Write() 命令,但是,这会暂停线程和 Windows From 停止直到设备响应,这有时可能很长,而事件处理程序将异步执行此操作。

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

我的问题 我怎样才能让 SerialDataReceivedEventHandler 识别 CurrentPosition()Speed() 中的哪一个引发了事件并将设备响应分别放入 positionspeed

解决方法

我认为您应该保持上次发送哪个命令的状态,例如使用枚举。 或者发送方应该添加(如果可能)请求的参数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。