TThread.Synchronize Makes Form Freezes

179 Views Asked by At

I'm checking how write to a Memo from a thread as safe mode. The problem is, when using TThread.Synchronize it make form freezes, and without that Form works good.

Here is the code who freeze:

procedure TestThread;
var
  x : Integer;
begin
  for x := 0 to 2 do
  begin
    TThread.CreateAnonymousThread(
    procedure
    begin
      while True do
      begin
        TThread.Synchronize(TThread.CurrentThread, procedure
        begin
          //CritLock.Acquire;
          try
            Form1.Memo1.Lines.Add('Add to Memo ' + IntToStr(GetTickCount));
          finally
            //CritLock.Release;
          end;
        end);
      end;
    end).Start;
  end;
end;

and here the code who don't freeze:

procedure TestThread;
    var
      x : Integer;
    begin
      for x := 0 to 2 do
      begin
        TThread.CreateAnonymousThread(
        procedure
        begin
          while True do
          begin
            //CritLock.Acquire;
            try
              Form1.Memo1.Lines.Add('Add to Memo ' + IntToStr(GetTickCount));
            finally
              //CritLock.Release;
            end;
          end;
        end).Start;
      end;
    end;
1

There are 1 best solutions below

0
On BEST ANSWER

Your 1st example is technically correct, the worker threads are safely updating the Memo in a proper way.

The problem is, they are updating it TOO MUCH. Your threads are running continuous loops at full speed, flooding the main thread's message queue with synchronization requests, making it nearly impossible for the main thread to handle other UI messages in a timely manner, such as painting the UI.

The sleep helps by slowing down the worker threads to give the main thread some much-needed breathing space to do other things in between syncs. In real-world production code, worker threads would not be slamming the UI with updates as hard as you are doing. They would be doing other meaningful work and notifying the UI with status updates only when needed.