Delphi: Form becomes Frozen while assigning strings in thread

两盒软妹~` 提交于 2019-12-13 16:07:08

问题


A code below is in a thread.

Tf1 := TFileStream.Create(LogsPath,fmOpenRead or fmShareDenyNone);
...
str:=TStringList.Create;
str.LoadFromStream(tf1);
...
SynEditLog.Lines.Assign(str); // I do this with Synchronize

There are 30 000 strings in a text document.

A form becomes frozen while assigning those strings to SynEdit.

If to load string by string it takes me 40 sec... If to use Assign - 8 sec.

How to prevent this form's state?

Thanks!!!


回答1:


I don't think Application.ProcessMessages is going to help here at all, since all the work happens in the one call to Assign.

Does SynEditLog have BeginUpdate/EndUpdate methods? I'd use them and see how you go. For instance:

SynEditLog.BeginUpdate;
try
  SynEditLog.Lines.Assign(str);
finally
  SynEditLog.EndUpdate;
end;

In response to that not working

You'll need to break down the assignment of the string list to the Lines property. Something like this:

var
  LIndex: integer; 
begin
  SynEditLog.BeginUpdate;
  try
    //added: set the capacity before adding all the strings.
    SynEditLog.Lines.Capacity := str.Capacity;
    for LIndex := 0 to str.Count - 1 do
    begin
      SynEditLog.Lines.Add(str[LIndex]);
      if LIndex mod 100 = 0 then
        Application.ProcessMessages;
    end;
  finally
    SynEditLog.EndUpdate;
  end;
end;

(note: code typed directly into browser, may not compile)

If this is too slow, try increasing the LIndex mod 100 = 0 to something larger, like 1000 or even 5000.

N@




回答2:


The form is freezing because you're using the GUI thread to add 30,000 lines to your control, which naturally takes a while. During this time, the GUI can't update because you're using its thread, so it looks frozen.

One way around this would be to add a few lines (or just one) at a time, and, in between each add, update the GUI (by calling Application.ProcessMessages (thanks gordy)).



来源:https://stackoverflow.com/questions/6728234/delphi-form-becomes-frozen-while-assigning-strings-in-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!