[Lazarus] Reading and writing TMemoryStream in events?

Bo Berglund bo.berglund at gmail.com
Sat Nov 6 09:54:20 CET 2010


I intended to use a TMemoryStream object to collect incoming serial
port data, but now I am not so sure it will be possible...

The problem as I see it is illustrated as follows:
In the event of the serial port component:

  s := FComm.ReadData;
  FMemStr.Seek(0, soFromEnd);  // To make sure we write at the end
  FMemStr.WriteBuffer(s[1], Length(s);

Then in the program waiting for the data to arrive:

  T1 := GetTickCount;
  while FMemStr.Position = 0 do
  begin
    Sleep(10);
    if GetTickCount - T1 > FCommTimeout then break;
  end;
  if FMemStr.Position = 0 then exit;
  FMemStr.Seek(0, soFromBeginning); //Read first byte
  C := FMemStr.ReadByte;

PROBLEM:
What will happen if a receive event is fired between the FMemStr.Seek
and C := FMemStr.ReadByte statements?

If the event handler does its thing then the memory stream pointer
will have been moved to a different value (end of stream) and the
ReadByte call will fail, right?

How can I avoid this from happening?


Bo Berglund





More information about the Lazarus mailing list