gpt4 book ai didi

multithreading - 时序和 VCL 同步(在/从线程)

转载 作者:行者123 更新时间:2023-12-03 18:27:15 41 4
gpt4 key购买 nike

我想刷新 Treenode.text (耗时)并使用来自同一线程的计时器。正如我所读到的,它不建议在线程中使用 TTimer*,但是,用什么来代替呢?谢谢你。

*我想使用一些时间而不是 sleep()。不仅因为那很俗气(?),而且我必须这样做,因为否则我只能在每一秒内刷新 treenodetext。)>>

unit master_slave

...

Tsrch_slave_thread = class(TThread)
protected
procedure Execute; override;
public
master: TMaster;
end;

TMaster = class(TObject)
private
...
FMasterNode: TTreeview;
Fsw: TStopWatch;
Fslave_search_thread : Tsrch_slave_thread;
...
end;

...

implementation

...

procedure Tsrch_slave_thread.Execute;
var
searchactive: integer;
begin
while not terminated do begin
searchactive := master.CMD_LISTCNT
if searchactive = 1 then //(master.CMD_LISTCNT's return value = 1, if master finished search on the bus)
exit;
sleep(1000); //dont want to flood the master with UDP packets... (master.CMD_LISTCNT sends UDP packets)
synchronize(procedure begin
with FmasterNode do
text := text + floattostr(Fsw.ElapsedMilliseconds / 1000);
end);
end;
end;

最佳答案

而不是 Sleep(1000) ,使用等待事件。

例如 TSimpleEvent .

FMySimpleEvent.WaitFor(1000);

如果你想提前退出线程,覆盖 TThread.DoTerminate方法和调用:
FMySimpleEvent.SetEvent;

像这样的东西:
procedure Tsrch_slave_thread.Execute;
var
searchactive: integer;
begin
while not terminated do begin
searchactive := master.CMD_LISTCNT
if searchactive = 1 then (master.CMD_LISTCNT's return value = 1, if search finished)
exit;
if (FMySimpleEvent.WaitFor(1000) = wrTimeOut) then
synchronize(procedure begin
with FmasterNode do
text := text + floattostr(Fsw.ElapsedMilliseconds / 1000);
end);
end;
end;

procedure Tsrch_slave_thread.DoTerminate;
begin
Inherited;
FMySimpleEvent.SetEvent;
end;

关于multithreading - 时序和 VCL 同步(在/从线程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21781941/

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