I have a race condition or something like it. I mean if I toggle a breakpoint before reading from COM, everything is good. But when i'm toggling it off, it freezes. writing:
public void Send(ComMessage message)
{
byte[] bytes = message.Serialise();
if (!_outputPort.IsOpen)
_outputPort.Open();
try
{
byte[] size = BitConverter.GetBytes(bytes.Length);
_outputPort.Write(size, 0, size.Length);
_outputPort.Write(bytes, 0, bytes.Length);
}
finally
{
if (_outputPort != _inputPort)
_outputPort.Close();
}
}
reading
private void InputPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
var port = (SerialPort) sender;
byte[] sizeBuffer = new byte[sizeof(long)];
port.Read(sizeBuffer, 0, sizeBuffer.Length);
int length = BitConverter.ToInt32(sizeBuffer, 0);
byte[] buffer = new byte[length];
int i = 0;
while (i < length)
{
int readed = port.Read(buffer, i, length - i);
i += readed;
}
var message = ComMessage.Deserialize(buffer);
MessageReceived(this, message);
}
for example, message has 625 bytes length. If I toggle a breakpoint, port.BytesToRead is equal 625, but if I disable it, byte count is 621.
Strange, but it works for a little amount of bytes (for short messages), but doesn't for long.
Please, advice.
sizeBuffer.Lengthbytes. You need to get the int returned from from Read and use that. You are not guaranteed what was sent on one side will be received as one message on the other side.Readto see how many bytes it read. It may have read less thansizeof(long)bytes in. Also you are making a buffer of sizelongbut long isInt64, you are callingToInt32. You should be either doingsizeof(int)or even better to make it more obvioussizeof(Int32)