Search code examples
delphitcomport

Delphi TComPort WriteAsync


I am trying to send a string through TComPort component asynchronously, but everything is sent synchronously. The issue is that the app will be blocked and wait until the transmission is over.

My code:

procedure TForm1.Button1Click(Sender: TObject);
var
  sss: string;
  i: Integer;
  t: cardinal;
begin
  sss:='';
  for i := 0 to 100 do
  begin
    sss:= sss + '1';
  end;

  memo1.Lines.Add('Str len - ' + IntToStr(Length(sss)));

  if self.MyPort1.Connected then
  begin
    InitAsync(Operation1);
    try
      self.MyPort1.WriteStrAsync(sss,Operation1);
      t:= GetTickCount;
      self.MyPort1.WaitForAsync(Operation1);
      t:= GetTickCount - t;
    finally
      DoneAsync(Operation1);
    end;    
    memo1.Lines.Add('Т - ' + IntToStr(t));
  end;
end;

Solution

  • Writing is asynchronous. But your call of WaitForAsync immediately after writing kills all the sense of asynchronous operation.

    If you need to be sure in completion of writing, make WaitForAsync before the next writing operation (or before another action that requires writing completion).

    In general - it is worth to wait for completion of overlapped operation in additional thread or use completion callback routine for notification