How to Link SerialPort Received Data to the Main UI thread's Read Function?
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 susp开发者_如何转开发end 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.
Just create a delegate and use it to send the data to a method where you can process the data recieved from serial port. My use case is i send a data over the port and i dont know when ill get the response back, it might be any time but at that time the data comes i should be able to get it and process it, so i do the following. Think this is what you might want
Public Delegate Sub recieveDelegate()
Private Sub datareceived1(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPrt.DataReceived
buffer = buffer & SerialPrt.ReadExisting()
If InStr(1, rxbuff, EOF) > 0 Then
Rxstring = rxbuff
rxbuff = ""
BeginInvoke(New recieveDelegate(AddressOf recieveHandlingMethod), New Object() {})
End If
End Sub
Just handle the data you recieve in the recieve handling method.
精彩评论