【问题标题】:Delphi FMX - HTTPS POST with AniIndicatorDelphi FMX - 使用 AniIndicator 的 HTTPS POST
【发布时间】:2021-02-08 17:03:23
【问题描述】:

在 Android 上,当我在 Indy https 发布功能期间触摸屏幕时,会出现“应用程序没有响应”。我不想看到它。我想在加载数据期间显示 AniIndicator 动画,而无需主线程忙。

我的代码:

function TFormMain.LoginChecker(iphttp: TIdHTTP): Boolean;
var
  s: string;
  Thread1: TThread;
begin
  Thread1 := TThread.CreateAnonymousThread
    (
    procedure
    begin

      TThread.Synchronize(Thread1,
        procedure
        begin
          s := iphttp.Post(ServerRoot + 'lc.php', TStream(nil));
        end);
    end);
  Thread1.Start;
  if Thread1.Finished then
  begin
    try
      if s = '1' then
        Result := True
      else
        Result := False;
    except
      Result := False;
    end;
  end;
end;

procedure TFormMain.Button2Click(Sender: TObject);
var
  Thread1: TThread;
  Logined: Boolean;
begin
  try
    AniIndicator1.Visible := True;
    AniIndicator1.Enabled := True;
    TabControl1.Visible := False;

    Logined:= LoginChecker(IdHTTP1);
    if Logined then
      ShowMessage('Yes!')
    else
      ShowMessage('No');
  finally
    AniIndicator1.Visible := False;
    AniIndicator1.Enabled := False;
    TabControl1.Visible := True;
  end; 

【问题讨论】:

  • 为什么要在 Synchronize 中调用 Post?这完全违背了使用线程的目的。这不是您代码中的唯一问题......但它是核心问题

标签: android multithreading delphi post firemonkey


【解决方案1】:

您正在向主线程Synchronize() 执行TIdHTTP.Post() 操作,这将阻塞您的UI,直到HTTP 操作完成。不要那样做。创建工作线程的全部意义在于在另一个线程中运行代码。所以让线程正常运行,当有值得报告的事情时通知主线程。

试试类似的方法:

function TFormMain.BeginLogin;
begin
  AniIndicator1.Visible := True;
  AniIndicator1.Enabled := True;
  TabControl1.Visible := False;

  TThread.CreateAnonymousThread(
    procedure
    var
      Logined: Boolean;
    begin
      Logined := False;
      try
        Logined := (IdHTTP1.Post(ServerRoot + 'lc.php', TStream(nil)) = '1');
      finally
        TThread.Queue(nil,
          procedure
          begin
            LoginFinished(Logined);
          end
        );
      end;
    end
  ).Start;
end;

procedure TFormMain.LoginFinished(Logined: Boolean);
begin
  if Logined then
    ShowMessage('Yes!')
  else
    ShowMessage('No');

  AniIndicator1.Visible := False;
  AniIndicator1.Enabled := False;
  TabControl1.Visible := True;
end; 

procedure TFormMain.Button2Click(Sender: TObject);
begin
  BeginLogin;
end;

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2019-05-16
    相关资源
    最近更新 更多