ThreadSynchronize (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the Synchronize method for executing a procedure on the main thread that owns the GUI. WaitFor is used for waiting for the thread's termination.

Code

procedure TEnumeratorThread.AddNewNumberToMemo;
begin
  { Increase the 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 milliseconds. }
    Sleep(100);

    {
    Run the AddNewNumberToMemo procedure on the main thread--it makes
    it safe to access the 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;

Uses