为什么这个线程没有终止?

时间:2013-05-15 19:52:32

标签: delphi delphi-2010

我无法让这个帖子终止。我在哪里犯了错误?

type
  TThumbnailThread = class(TThread)
  public
    procedure Execute; override;
    procedure CreateContactSheets;
  end;

procedure TThumbnailThread.Execute;
begin
  while not Terminated do
  begin
     CreateContactSheets;
     Synchronize(CreateContactSheets);
  end;
end;

procedure TThumbnailThread.CreateContactSheets;
const
  iColumns: integer = 6;
  iRows: integer = 6;
  iHorzontalSpace: integer = 0;
  iVerticalSpace: integer = 0;
  iHorzontalMargin: integer = 0;
  iVerticalMargin: integer = 0;
  iDrawBox: boolean = true;
  iDrawText: boolean = True;
  iDrawShadow: boolean = True;
  iBackgroundColor: TColor = clWhite;
  iBoxColor: TColor = clBlack;
  iPageNo: Integer = -1;
begin
  Form1.ImageEnMView1.MIO.PrintImagesToFile(Form1.AThumbnailFilename, 80, Screen.Width,
      Screen.Height, iColumns, Rows, iHorzontalSpace, iVerticalSpace,
      Form1.PrintSelected1.Checked, iHorzontalMargin, iVerticalMargin, iDrawBox, iDrawText,
      iDrawShadow, iBackgroundColor, iBoxColor, iPageNo);
end;

procedure TForm1.PrintToFile1Click(Sender: TObject);
begin
  if SavePictureDialog1.Execute then
  begin
    if SavePictureDialog1.FileName <> '' then
    begin
      Screen.Cursor := crHourGlass;
      try
        iFilename := SavePictureDialog1.FileName;
        { If one thread have been started already, we don't start another. }
        if ThumbnailThread <> nil then
          raise Exception.Create('One thread has already been started!');
        AThumbnailFilename := iFilename;
        ThumbnailThread := TThumbnailThread.Create(false);
        ThumbnailThread.OnTerminate := TerminateTheThread;
      finally
        Screen.Cursor := crDefault;
      end;
    end;
  end;
end;

procedure TForm1.Abort1Click(Sender: TObject);
begin
  ThumbnailThread.Terminate;
  ProgressBar1.Position := 0;
  Screen.Cursor := crDefault;
end;

procedure TForm1.TerminateTheThread;
begin
  Form1.ImageEnMView1.MIO.Aborting := True;
end;

1 个答案:

答案 0 :(得分:2)

绝对没有理由在这里有一个主题。您正在使用synchronized方法执行所有工作,该方法在运行时停止主线程。你正在创建一个不做任何事情的线程,只是暂停自己在主线程中运行一些东西。

您的线程没有终止,因为Form1.ImageEnMView1.MIO.PrintImagesToFile无法检查是否已设置Thread.Terminate变量,因此只要PrintImagesToFile运行,就不会检查该标志。由于线程已暂停,因为您正在运行一个synchronized方法(在主线程的上下文中运行),因此线程永远不会知道它已在所有工作完成之后终止。