如何在没有Synchronize的情况下使用Delphi版本(Pre Delphi 2010)更新GUI控件

Bil*_*ill 0 delphi multithreading vcl delphi-2010 delphi-xe4

我有一些使用Delphi 2010和XE4构建的应用程序,它们在一个线程中使用Synchronize.我认为在Delphi 2010中将Synchronize引入了Delphi.我的线程运行得很好,所以这不是问题.

我的问题是:有没有办法在Delphi 2010之前与Delphi版本"同步"或者以不同的方式询问它,如何在没有Synchronize的情况下更新这些早期版本的Delphi中的GUI控件?

下面显示的代码是实际代码的子集,以减少此帖子的长度.

type
  { A TThread descendent for loading Images from a folder }
  TFolderLoadingThread = class(TThread)
  private
    { Private declarations }
    AspectRatio: double;
  protected
    { Protected declarations }
    procedure Execute; override;
  public
    { Public declarations }
    constructor Create(CreateSuspended: Boolean);
  end;

procedure TFolderLoadingThread.Execute;
{ Load images ImageEnView in the thread. }
begin
  inherited;
  { Free the thread onTerminate }
  FreeOnTerminate := True;
  if not Terminated then
  begin
    { Set the Progressbar.Max Value }
    **Synchronize**(
      procedure
      begin
         if iFileCount > 0 then
          Form1.Gauge1.MaxValue := iFileCount - 1;
 end);
end;
Run Code Online (Sandbox Code Playgroud)

MBo*_*MBo 6

Synchronize是非常老的例程,但在D2009之前的Delphi版本中没有匿名过程.Synchronize旨在调用这些版本中没有参数的方法.

procedure TFolderLoadingThread.UpdateProgress;
begin
 if iFileCount > 0 then
          Form1.Gauge1.MaxValue := iFileCount - 1;
end;
Run Code Online (Sandbox Code Playgroud)

在执行中:

do thead work...
Synchronize(UpdateProgress);
Run Code Online (Sandbox Code Playgroud)

PS你不必在Execute体中调用Terminate

  • 换句话说:将同步代码移动到该线程类的单独方法,并通过Synchronize调用此方法. (4认同)