Async sample (Delphi)

Overview

This sample demonstrates how to call methods on a Remoting SDK server asynchronously using _Async interface. This means that the main application thread is not blocked while waiting for the method execution results. This may be especially useful in cases where the operation takes a significant amount of time, so you may submit a request and defer receiving the result for later without creating background threads.

In this sample a very simple calculation is performed, but there is a ten seconds delay in the method so it is possible to query the server before the calculation is completed.

Getting Started

  • Compile and launch the server.
  • Compile and run the client.
  • Click on the Calc Live button to verify that the connection works. Notice that the application, its window and all controls in it are frozen until the result is returned.
  • Try one or several of the Calc Async buttons and then try checking and/or receiving the result before and after ten seconds have passed. Notice that the application is not frozen, unlike after clicking the Calc Live button.

Examine the code

  • Look how the async request to the server is initiated by calling the Invoke_MethodName procedure:
procedure TAsyncClientMainForm.CalcAsyncHttpButtonClick(Sender: TObject);
begin
  Screen.Cursor := crHourGlass;
  try

    if not Assigned(fAsyncService) then
      fAsyncService := CoAsyncService_Async.Create(ROBINMessage1, ROWinInetHTTPChannel1);

    ed_Result.Text := '';
    ed_Result.Repaint();

    fAsyncService.Invoke_Sum(StrToInt(ed_Value1.Text), StrToInt(ed_Value2.Text));
    AdjustButtons();

  finally
    Screen.Cursor := crDefault;
  end;

  ShowMessage('The request has been sent to the Server.'#13'Click "Retrieve Result" to check if an answer has been received yet.');
end;
  • Notice how to check if the result of the async call is obtained and how to get it with the Retrieve_MethodName method:
procedure TAsyncClientMainForm.GetResultButtonClick(Sender: TObject);
begin
  if not Assigned(fAsyncService) then exit;

  Screen.Cursor := crHourGlass;
  try

    if fAsyncService.AnswerReceived then begin
      ed_Result.Text := IntToStr(fAsyncService.Retrieve_Sum());
      fAsyncService := nil;
      lbl_Status.Caption := 'Idle';
    end
    else begin
      ShowMessage('Sorry, no answer yet.');
    end;
    AdjustButtons();

  finally
    Screen.Cursor := crDefault;
  end;
end;