For loop 并行。For比For循环花费的时间更长

For loop 并行。For比For循环花费的时间更长,for-loop,omnithreadlibrary,For Loop,Omnithreadlibrary,在Delphi Berlin 10.1中,我有一个for循环: for i := 0 to slSMP.Count - 1 do begin if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisS

在Delphi Berlin 10.1中,我有一个
for
循环:

for i := 0 to slSMP.Count - 1 do
begin
  if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
    System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
  begin
    slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
  end;
end;
OtlParallel.Parallel.For(0, slSMP.Count - 1).Execute(
  procedure (i: integer)
  begin
    if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
      System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
    begin
      slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
      //CodeSite.Send('TformSearchStartMenu.DoSearchFromSearchEdit: i', i);
    end;
  end);
slSMP和slTempSearchList显然属于
TStringList
类型

不幸的是,这个循环花费了太多时间,所以我决定将其转换为
OtlParallel.Parallel.For
循环:

for i := 0 to slSMP.Count - 1 do
begin
  if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
    System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
  begin
    slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
  end;
end;
OtlParallel.Parallel.For(0, slSMP.Count - 1).Execute(
  procedure (i: integer)
  begin
    if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
      System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
    begin
      slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
      //CodeSite.Send('TformSearchStartMenu.DoSearchFromSearchEdit: i', i);
    end;
  end);
奇怪的是,当
CodeSite.Send
行被停用时,这个循环永远不会结束,所以我不得不用任务管理器关闭应用程序

但是当
CodeSite.Send
行被激活时,循环结束,但它比简单的
for
循环需要更长的时间

那么,如何通过并行编程加快循环速度呢?
 
为什么
OtlParallel.Parallel.For
仅在激活
CodeSite.Send
行时才起作用?如果没有
代码站点,如何使其工作。发送
行?

代码看起来很好,程序不应该挂起。如果没有一个可复制的测试用例,就无法解释原因。当然,如果在每个循环中将信息发送到代码站点,它的工作速度会变慢。可能会变慢,因为设置后台线程需要时间。因此,使其并行工作只会对大型列表有利。此外,我担心slTempSearchList,如果它在线程之间共享,您将遇到严重的竞争条件问题。