哪个是初始化代码的最佳位置? [英] Which is the best place to initialize code?
问题描述
哪个是初始化代码(例如加载INI文件)的最佳位置?我想首先在屏幕上显示该表单,以便用户知道该应用程序正在加载,然后才要调用冗长的函数,例如LoadIniFile或IsConnectedToInternet(最后一个确实很慢)。
Which is the best place to initialize code such as loading INI file? I want first to show the form on screen so the user know that the app is loading and ONLY after that I want to call lengthy functions such as LoadIniFile or IsConnectedToInternet (the last one is REALLY slow).
OnCreate不好,因为该表单尚未准备好,它不会显示在屏幕上。
The OnCreate is not good because the form is not yet ready and it will not show up on screen.
我这样做是DPR,但不是始终工作:
I do this I DPR but not working always:
program Test;
begin
Application.Initialize;
Application.Title := 'Test app';
Application.CreateForm(TfrmTest, frmTest);
frmTest.Show; <---------------------- won't show
LateInitialize;
Application.Run;
end.
在执行LateInitialize(4-5秒)之前,不会显示该表单。
The form will not show until LateInitialize (4-5 seconds) is executed.
procedure LateInitialize;
begin
CursorBussy;
TRY
// all this won't work also. the form won't show
frmTest.Visible:= TRUE;
Application.ProcessMessages;
frmTest.Show;
Application.ProcessMessages;
frmTest.BringToFront;
frmTest.Update;
Application.ProcessMessages;
DoSomethingLengthy; {4-5 seconds}
FINALLY
CursorNotBussy;
END;
end; <--------- Now the form shows.
是的,frmTest是我唯一的形式(主要形式)。
And yes, frmTest it is my only form (the main form).
推荐答案
调用 frmTest.Show
后,可以调用 frmTest.Update
使其呈现在屏幕上,然后调用 LateInitialize
。但是,在调用 Application.Run
之前,主消息循环将不会运行,因此该表单在此之前将无法执行其他任何操作。
After calling frmTest.Show
, you can call frmTest.Update
to let it render onscreen, before then calling LateInitialize
. But until Application.Run
is called, the main message loop will not be running, so the form will not be able to do anything else until then.
另一种选择是使用表单的 OnShow
事件,通过 PostMessage将自定义窗口消息发布回表单。 )
,然后在以后收到该消息时,调用 LateInitialize
的形式。这将允许表单正常处理绘画消息,直到调用 LateInitialize
。
Another option is to use the form's OnShow
event to post a custom window message back to the form via PostMessage()
, then have the form call LateInitialize
when it receives that message at a later time. That will allow the form to process painting messages normally until LateInitialize
is called.
任何阻止主线程实际上应该将超过几毫秒/秒的时间移到单独的工作线程中(尤其是 IsConnectedToInternet
之类的东西)。主线程应用于运行UI。
Anything that blocks the main thread for more than a few milliseconds/seconds really should be moved into a separate worker thread instead (especially things like IsConnectedToInternet
). The main thread should be used for running the UI.
这篇关于哪个是初始化代码的最佳位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!