gpt4 book ai didi

c# - serialPort_DataReceived 事件的问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:29 24 4
gpt4 key购买 nike

我在通信类下有一个函数

    public int SerialCommunciation()
{
/*Function for opening a serial port with default settings*/
InitialiseSerialPort();

/*This section of code will try to write to the COM port*/
WriteDataToCOM();

/*An event handler */
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

return readData;
}

这里

     int readData /*is a global variable*/

_serialPortDataRecieved()根据从串口读取的数据更新变量readData

   /* Method that will be called when there is data waiting in the buffer*/
private void _serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{

string text = _serialPort.ReadExisting();
int.TryParse(text, out readData);

}

现在当我从另一个类调用这个函数时

   valueReadFromCom=Communication.SerialCommunication()

我需要从串行端口读取值,但我得到的是 0。当我尝试调试这段代码时,我发现控件首先转到语句

   return readData;

在函数 SerialCommunication 中,然后控制转到函数 _serialPort_DataRecieved,该函数由事件触发。我怎样才能使整个过程同步,这意味着 readData 应该仅在函数 _serial_DataRecieved 执行后从函数 serialCommunication 返回。

最佳答案

请注意,以下不是正确的方式,因为串口工作异步。另一方面,它无论如何都能完成工作。

只需添加一个 boolen 属性并在从 SerialCommunication 函数返回之前检查此属性;收到数据时将此属性设置为 true。

private bool dataReceived = false;   

public int SerialCommunciation()
{
/*Function for opening a serial port with default settings*/
InitialiseSerialPort();

/*This section of code will try to write to the COM port*/
WriteDataToCOM();

/*An event handler */
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

while (!dataReceived)
{
Thread.Sleep(1000);
}
return readData;
}

private void _serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string text = _serialPort.ReadExisting();
int.TryParse(text, out readData);
_serialPort_DataReceived = true;
}

关于c# - serialPort_DataReceived 事件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10848325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com