Im trying to read from a com port, this is my code
public string HouseState()
{
string state = string.Empty;
if (!Variables.portBusy)
{
// Begin communications
var blockLimit = 13;
openSerial();
byte[] buffer = new byte[blockLimit];
Action kickoffRead = null;
kickoffRead = delegate
{
serialPort.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar)
{
try
{
int actualLength = serialPort.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
state += System.Text.Encoding.UTF8.GetString(received);
//MessageBox.Show(state);
}
catch (IOException exc)
{
//handleAppSerialError(exc);
}
if (state.Count() <= 13)
kickoffRead();
}, null);
};
kickoffRead();
}
MessageBox.Show(state);
var index = state.IndexOf("R");
var command = string.Empty;
if (index >= 0)
command = state.Substring(index, 13);
return command;
}
What im trying to get is a string that starts with R and has 13 characters. Because sometimes the port sends half the string i do this: if (state.Count() <= 13)
But while inside BaseStream the state string gets what i want, when i try to read the string of state, it appears empty. The MessageBox shows an empty string.
why this is happening?