RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TThread.WaitFor Method

Waits for the thread to terminate and then returns the value of the ReturnValue property.

Pascal
function WaitFor: LongWord;
C++
__fastcall LongWord WaitFor();

Call WaitFor to obtain the value of ReturnValue when the thread finishes executing. WaitFor doesn't return until the thread terminates, so the thread must exit either by finishing the Execute method or by exiting when the Terminated property is true.  

C++ Examples: 

 

/*
This example demonstrates the use of Synchronize method to execute a procedure
on the main thread that "owns" the GUI. Also WaitFor is used to wait for the
thread's termination.
*/
__fastcall TEnumeratorThread::TEnumeratorThread(TMemo* Memo)
    : TThread(true)
{
    /* Initialize internal fields */
    m_Memo = Memo;
    m_CurrNbr = 0;
    m_Stop = 0;
}

void __fastcall TEnumeratorThread::Execute()
{
    /* Repeat the loop until the flag says otherwise */
    while (!m_Stop)
    {
        /* Wait for 100 milli */
        Sleep(100);

        /*
        Run AddNewNumberToMemo procedure on the main thread - makes
        it safe to access GUI from this thread.
        */
        Synchronize(AddNewNumberToMemo);
    }

    m_Stop = 0;
}

void __fastcall TEnumeratorThread::GentleStop()
{
  /* Set the flag to 1 */
  InterlockedIncrement(&m_Stop);

  /* Wait for this thread to finish executing */
  this->WaitFor();
}

void __fastcall TEnumeratorThread::AddNewNumberToMemo()
{
  /* Increase current number and add it to the memo */
  m_CurrNbr++;
  m_Memo->Lines->Add(IntToStr(m_CurrNbr));
}

 

Delphi Examples: 

{
This example demonstrates the use of Synchronize method to execute a procedure
on the main thread that "owns" the GUI. Also WaitFor is used to wait for the
thread's termination.
}
procedure TEnumeratorThread.AddNewNumberToMemo;
begin
  { Increase current number and add it to the memo }
  Inc(FCurrNbr);
  FMemo.Lines.Add(IntToStr(FCurrNbr));
end;

constructor TEnumeratorThread.Create(const Memo: TMemo);
begin
  { Initialize internal fields }
  FMemo := Memo;
  FCurrNbr := 0;
  FStop := 0;

  inherited Create(true);
end;

procedure TEnumeratorThread.Execute;
begin
  { Repeat the loop until the flag says otherwise }
  while FStop = 0 do
  begin
    { Wait for 100 milli }
    Sleep(100);

    {
    Run AddNewNumberToMemo procedure on the main thread - makes
    it safe to access GUI from this thread.
    }
    Synchronize(AddNewNumberToMemo);
  end;

  FStop := 0;
end;

procedure TEnumeratorThread.GentleStop;
begin
  { Set the flag to 1 }
  InterlockedIncrement(FStop);

  { Wait for this thread to finish executing }
  Self.WaitFor;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!