Nevermore
Nevermore

Reputation: 1743

How to wait thread finish

hello this is my main thread :

 procedure TShareWithForm.btnShareClick(Sender: TObject);
begin
  Panel1.Visible:= True;

  if SelectedUserID = '' then
  begin
    Exit;
  end;

  TUploadThread.Create(Self);

  Panel1.Visible:= False;

    FormMain.CaseListMyShares;
    Close;
  end;
end;

And my execute method in thread:

procedure TUploadThread.Execute;
var
  i: Integer;
  CaseId: String;
  tmpFilePath: String;

  curr_cases: Integer;

  obContextIO: TContextIO;

  workingDir: String;
begin

  obShareApiAdapter.IdHTTPWorkBeginEvent:= ShareWithForm.IdHTTP1WorkBegin;
  obShareApiAdapter.IdHTTPWorkEvent:= ShareWithForm.IdHTTP1Work;
  obShareApiAdapter.IdHTTPWorkEndEvent:= ShareWithForm.IdHTTP1WorkEnd;

  curr_cases:= -1;
  SetLength(FForm.SelectedCases, FForm.ShareGrid.RowCount -1);

  for i := 1 to FForm.ShareGrid.RowCount - 1 do
  begin
    CaseId:= FForm.ShareGrid.Cells[0, i];

    if CaseId = '' then
      continue;

    if FormMain.AExists then
        workingDir:= obPath.ServerData + CaseId
    else
        workingDir:= obPath.CaseBackupPath + '\' + CaseId;

    TZipFile.ZipDirectoryContents(obPath.CaseTmpPath + '\' + CaseId + '.zip', workingDir);
    Inc(curr_cases);
    FForm.SelectedCases[curr_cases].patientCase:= CaseId;
    FForm.SelectedCases[curr_cases].rawFile:= obShareApiAdapter.AddNewFile(obPath.CaseTmpPath + '\' + CaseId + '.zip');
  end;
end;

When i start to thread, i want to wait thread finish then run this codes :

Panel1.Visible:= False;

    FormMain.CaseListMyShares;
    Close;

But thread is running parallel.. When i show the Panel1 then thread execute, mainthread has to wait thread finish.

How can i wait thread finish its job?

Panel1 contains a LOADING GIF.

Upvotes: 0

Views: 235

Answers (2)

LU RD
LU RD

Reputation: 34939

How can i wait thread finish its job?

Use an event driven design. Add an OnTerminate event handler for your thread, where you handle what will happen after the thread is finished.


Note: There are several flaws in your thread execute handler. All of them are due to direct access of GUI components. That is not allowed.

Instead, transfer all that information during the thread creation. If you need to update the GUI from the thread, use Synchronize or Queue methods.

Upvotes: 5

gordy
gordy

Reputation: 9806

defeats the purpose of using a thread but you could

TUploadThread.Create(Self).WaitFor();

Upvotes: -1

Related Questions