繁体   English   中英

如何处理DataReceived

[英]How to handle DataReceived

请参阅下面的代码,我试图返回到注册端口的DataReceived事件的方法。 基本上,如果我在读取超时之前从端口接收数据。 我将返回注册DataReceived事件和degister的位置,然后继续进行处理。 我正在尝试使用while循环。 但不确定是否准确,这是必须执行的方法,或者是否有其他方法可以执行此操作。

public class CommClass{
private static byte[] portReturn = null;

private void setUpDevice()
{
    byte[] command = { 0x11,0X51 };
    try
    {
        port.DataReceived += new SerialDataReceivedEventHandler(serialPortDataReceived);
        port.Write(command, 0, command.Length);
        while (portReturn == null) { } //Not sure if this will work. If I receive data before times out I do not want to wait in the loop.
        port.DataReceived -= serialPortDataReceived;
    }
    catch(Exception ex)
    {
        //to do
    }
}


private void serialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    var servicePort = (SerialPort)sender;
    portReturn = servicePort.ReadByte();
    return;
}
}

您的代码将在技术上有效; 但是,当您等待数据进入时,while循环将使CPU最大化,这不是您想要的。 我建议在此处使用ManualResetEvent ,让您等待以CPU友好的方式接收数据。 您可以在这里阅读更多有关它们的信息

public class CommClass
{
    private static byte[] portReturn = null;

    // ManualResetEvents are great for signaling events across threads
    private static ManualResetEvent dataReceivedEvent = new ManualResetEvent(false);

    private void setUpDevice()
    {
        byte[] command = { 0x11,0X51 };
        try
        {
            port.DataReceived += new SerialDataReceivedEventHandler(serialPortDataReceived);
            port.Write(command, 0, command.Length);

            // Wait for the event to be set without spinning in a loop.
            // Can also specify a timeout period to wait in case the data never comes.
            dataReceivedEvent.WaitOne();

            // Reset the event so that you can use it again later if necessary
            dataReceivedEvent.Reset();

            port.DataReceived -= serialPortDataReceived;
        }
        catch(Exception ex)
        {
            //to do
        }
    }


    private void serialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        var servicePort = (SerialPort)sender;
        portReturn = servicePort.ReadByte();

        // Set the event to let the main thread know you have received data
        dataReceivedEvent.Set();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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