gpt4 book ai didi

delphi - 如何在delphi 10中的任务线程内使用for循环

转载 作者:行者123 更新时间:2023-12-03 15:28:20 25 4
gpt4 key购买 nike

如何在 TTask 中正确使用 for 循环?我总是只获取备忘录中 ListBox1 的最后一项,例如,如果 ListBox1 中有 5 个项目,我会在 memo1 中获取 ListBox1 最后一项 5 次!代码有什么问题吗?

var
i: Integer;
lPath: string;
begin
for i := 0 to ListBox1.Items.Count - 1 do
begin
lPath := ListBox1.Items.Strings[i];
TTask.Create(
procedure
var
lHTTP: TIdHTTP;
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
begin
lHTTP := TIdHTTP.Create(nil);

TThread.Synchronize(nil,
procedure
begin
Form1.Caption := 'Task Running...';
end
);

try
lHTTP.ReadTimeout := 30000;
lHTTP.HandleRedirects := True;
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
IdSSL.SSLOptions.Method := sslvTLSv1;
IdSSL.SSLOptions.Mode := sslmClient;
lHTTP.IOHandler := IdSSL;
Finally
try
lHTTP.Get('http://website.com/'+lPath, TStream(nil));
Finally
lHTTP.Free;
end;
end;

TThread.Synchronize(nil,
procedure
begin
Memo1.Lines.Add(lPath);
end
);

end
).Start;

end;
end;

最佳答案

这是改编后的代码:

// Current method:
procedure TMyForm.XYZ
var
i: Integer;
lPath: string;
begin
for i := 0 to ListBox1.Items.Count - 1 do
begin
lPath := ListBox1.Items.Strings[i];
StartDownloadTask(lPath);
end;
end;

// Put task creation in separate method:
procedure TMyForm.StartDownloadTask(lPath: string)
begin
TTask.Create(
procedure
var
lHTTP: TIdHTTP;
IdSSL: TIdSSLIOHandlerSocketOpenSSL;
begin
lHTTP := TIdHTTP.Create(nil);

TThread.Synchronize(nil,
procedure
begin
Form1.Caption := 'Task Running...';
end
);

try
lHTTP.ReadTimeout := 30000;
lHTTP.HandleRedirects := True;
IdSSL := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
IdSSL.SSLOptions.Method := sslvTLSv1;
IdSSL.SSLOptions.Mode := sslmClient;
lHTTP.IOHandler := IdSSL;
Finally
try
lHTTP.Get('http://website.com/'+lPath, TStream(nil));
Finally
lHTTP.Free;
end;
end;

TThread.Synchronize(nil,
procedure
begin
Memo1.Lines.Add(lPath);
end
);

end
).Start;
end;

有关背景的说明请参阅 https://stackoverflow.com/a/13349520/101087 中的说明

其他答案中最重要的部分:

Note that variable capture captures variables—not values. If a variable's value changes after being captured by constructing an anonymous method, the value of the variable the anonymous method captured changes too, because they are the same variable with the same storage.

To capture the value of the loop variable, wrap creation of the task in a separate function:

关于delphi - 如何在delphi 10中的任务线程内使用for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com