I’d like to know how to link the data received via serialport to the function calling it in the main UI.
I would like the UI to send out data from the serialport, then suspend the thread or wait until data is received via the serialport thread, before continuing the main UI thread.
I am told that thread.suspend() is not a safe function to use, I tried it together with thread.resume, but failed.
Should I be looking at lock/mutex?
Or EventWaitHandles?
I am thoroughly confused! I am not familiar with threading so any help would be much appreciated! Thank you.
Code below:
public static int SerialCOM_Read(uint tRegisterAddress, out byte[] tRegisterValue, uint nBytes)
{
int retVal = 1;
tRegisterValue = new byte[nBytes];
byte[] nBytesArray = new byte[4];
NBytes = nBytes;
try {
ReadFunction = true;
YetToReceiveReadData = true;
byte[] registerAddress = BitConverter.GetBytes(tRegisterAddress);
int noOfBytesForRegAdd = 1;
if (registerAddress[3] > 0) noOfBytesForRegAdd = 4;
else if (registerAddress[2] > 0) noOfBytesForRegAdd = 3;
else if (registerAddress[1] > 0) noOfBytesForRegAdd = 2;
nBytesArray = BitConverter.GetBytes(nBytes);
{
Append_Start();
Append_Operation_with_NoOfBytesForRegAdd(OPERATION.I2C_READ, noOfBytesForRegAdd);
Append_RegAdd(noOfBytesForRegAdd, tRegisterAddress);
Append_NoOfBytesOfData(nBytesArray);
Send_DataToWrite();
//Need to Suspend Thread here and Continue once the
//ReadData[i] global variable has been assigned.
for(int i=0; i<nBytes; i++)
tRegisterValue[i] = ReadData[i];
}
catch(Exception ex) {}
return retVal;
}
If you are going to block the UI thread then there’s no point in using the DataReceived event. Simply call SerialPort.Read/Line() directly. The delays this can cause in the user interface responsiveness are usually undesirable but it is definitely a lot easier to get going.