How to animate a spinner while performing a workload via threading

家住魔仙堡 提交于 2019-12-04 20:18:24

Enable your spinner before starting the thread.

Define an OnTerminate method for your thread where you disable the spinner.

Do your work in the thread and when it is ready, the OnTerminate takes care of removing the spinner.

Note: There is no need to explicitly free your thread, since FreeOnTerminate is true.

begin
  if btnLogin.Text = 'Login' then begin
    Form_Login.LoadSpinnerFrame.visible := True;
    Form_Login.LoadSpinner.Visible := True;
    Form_Login.LoadSpinner.Enabled := True;
    btnLogin.Enabled := False;
    aThread := TMyThread.Create(True);
    aThread.FreeOnTerminate := true;
    aThread.OnTerminate := Self.WorkIsDone;
    aThread.Start;
  end 
  else begin
    btnLogin.Text := 'Login';
  end; 

procedure TYourForm.WorkIsDone(Sender : TObject);
begin
  Form_Login.LoadSpinnerFrame.visible := False;
  Form_Login.LoadSpinner.Visible := False;
  Form_Login.LoadSpinner.Enabled := False;
  btnLogin.Text := 'Logout';
  btnLogin.Enabled := True;
end;

procedure TMyThread.Execute;
begin
  // Make your work
end;

The important thing here is that the program flow is event driven. No polling required which can drain the CPU cycles and make the GUI unresponsive.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!