情境
为了更好地理解PPL和Task
的工作原理,我尝试编写了一个非常简单的程序。当您点击一个按钮时,会在ListBox
中填充磁盘上的目录列表。
procedure TForm3.Button1Click(Sender: TObject);
var proc: ITask;
begin
//Show that something is going to happen
Button1.Caption := 'Process...';
proc := TTask.Create(
procedure
var strPath: string;
sl: TStringDynArray;
begin
if (DirectoryExists('C:\Users\albertoWinVM\Documents\uni\maths')) then
begin
ListBox1.Items.Clear;
sl := TDirectory.GetDirectories('C:\Users\albertoWinVM\Documents\uni\maths',
TSearchOption.soAllDirectories, nil);
for strPath in sl do
begin
ListBox1.Items.Add(strPath);
end;
//At the end of the task, I restore the original caption of the button
Button1.Caption := 'Go';
Label1.Caption := 'Finished';
end;
end
);
proc.Start;
end;
你可以在上面看到maths
文件夹并不是很大,执行该任务大约需要3秒钟。该任务的声明如下:
type
TForm3 = class(TForm)
ListBox1: TListBox;
//... other published things var ...
private
proc: ITask;
public
//... public var ...
end;
问题
当我使用例如C:\Users\albertoWinVM\Documents
这样的路径来工作时,我有很多文件夹,程序要花费长达3分钟才能填满ListBox。
如果我关闭程序(而任务仍在运行),只有上面的代码,从我在网上阅读所了解的来看,任务仍将继续运行,直到它完成。我理解得对吗?
procedure TForm3.FormDestroy(Sender: TObject);
begin
proc.Cancel;
end;
我认为添加这段代码可以提高程序的安全性。这样就足够了吗?
BeginUpdate
和EndUpdate
在列表框上进行批量更新 - 更新每个项目可能会影响性能。这还自然地产生了一个很好的间隔,以便调用CheckCanceled
,以便.Cancel
能够及时使proc.Wait()
返回。 - J...