作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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/
我是一名优秀的程序员,十分优秀!