2

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

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;
4

1 回答 1

2

绝对没有理由在这里有一个线程。您正在同步方法中完成所有工作,该方法在主线程运行时停止它。您正在创建一个除了暂停自身以在主线程中运行某些东西之外什么都不做的线程。

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

于 2013-05-15T22:11:00.440 回答