我在类通信下有一个功能
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 返回。