Delphi专题 ·

Delphi线程优先级

描述

这个例子展示了如何创建一个线程并以低于主执行线程的优先级启动它。将线程的FreeOnTerminate属性设置为true,这样当线程完成时就不需要释放线程。必须将procedure Execute;Tthread的扩展类加入override(procedure Execute; override;),否则将导致“Abstract Error”。要创建它,请选择File > New > Other > Thread Object菜单
Delphi线程优先级 Delphi专题 第1张

主要代码

procedure TForm1.Button1Click(Sender: TObject);  //运行MyProcess
begin
if (mythreadRunning = False) then
  begin
    mythreadRunning := True;
    MyProcess := TMyThread.Create(True); { 创建线程并挂起. }
    MyProcess.FreeOnTerminate := True; { 运行结束后自动结束线程. }
    MyProcess.Priority := tpLower;  { 将优先级设置为低于正常值. }
    MyProcess.Resume; { 运行线程 }
  end
  else
    MessageDlg('此线程仍在运行!', mtInformation, [mbOk], 0);
end;

procedure TForm1.Button2Click(Sender: TObject); //主线程  运行后界面UI将冻结
var
  I: Integer;

begin
  Form1.Memo2.Lines.Add('在主流程中在10秒内运行一些工作:');
  for I := 0 to 10 do
  begin
    Form1.Memo2.Lines.Add('主线程: ' + InttoStr(I));
    Sleep(1000);
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);//运行YouProcess
begin
if (youthreadRunning = False) then
  begin
    youthreadRunning := True;
    YouProcess := TYouThread.Create(True); { 创建线程并挂起. }
    YouProcess.FreeOnTerminate := True; { 运行结束后自动结束线程. }
    YouProcess.Priority := tpLower;  { 将优先级设置为低于正常值. }
    YouProcess.Resume; { 运行线程. }
  end
  else
    MessageDlg('此线程仍在运行!', mtInformation, [mbOk], 0);
end;

procedure TForm1.Button4Click(Sender: TObject); //停止MyProcess
begin
if mythreadRunning then
MyProcess.Terminate();
end;

procedure TForm1.Button5Click(Sender: TObject); //停止YouProcess
begin
 if youthreadRunning then
 YouProcess.Terminate();
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
mythreadRunning := False;
youthreadRunning := False;
end;

{ TMyThread }
procedure TMyThread.Execute;
var
  I: Integer;
begin
  Form1.Memo1.Lines.Add('进程已运行了:');
  for I := 0 to 10 do
  begin
    if Terminated then break;
    Form1.Memo1.Lines.Add('低优先级进程 ' + InttoStr(I));
    Sleep(1000);
  end;
  mythreadRunning := False;

end;

{ TYouThread }
procedure TYouThread.Execute;
var
  I: Integer;

begin
  Form1.Memo3.Lines.Add('第二个低优先级进程已运行了:');
  for I := 0 to 10 do
  begin
    if Terminated then break;
    Form1.Memo3.Lines.Add('第二个低优先级进程 ' + InttoStr(I));
    Sleep(1000);
  end;
  youthreadRunning := False;
end;

相关下载

点击下载

参与评论