I have a function under class Communication
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;
}
Here
int readData /*is a global variable*/
The _serialPortDataRecieved() updates the variable readData according to the data read from serial port
/* 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);
}
Now when i called this function from another class
valueReadFromCom=Communication.SerialCommunication()
I needed to get the value read from serial port but instead i got 0.
When i tried debugging this code, i found out that control first goes to statement
return readData;
in function SerialCommunication and only then control goes to function _serialPort_DataRecieved, function triggered by event. How can i make the whole process synchronous, that means readData should be returned from the function serialCommunication only after the function _serial_DataRecieved is performed.
Be adviced that the following is not the right way as serial port works async. On the otherhand it does the job anyway.
Just add a boolen property and check this property before returning from SerialCommunication function; set this property to true when data is received.