multithreading - Determining that form is alive -
im have method of form loads data, data may take long time load. part of data optional , form can closed before data loaded:
procedure tform1.loaddata(sender: tobject); begin // load , add data form ... tthread.createanonymousthread(procedure begin // long data loading ... tthread.synchronize(nil, procedure begin // add data form ... end); end).start; end; and question: best method determine form alive (not closed) fmx avoid exception when data thread should added? long loading mean not hours or ten's minutes, can 1 minute.
update: after closing form don't need additional data anymore , thread can terminated. terminated in way, neet without exception. have
tthread.synchronize(nil, procedure begin // add data form try ... except end; end); and works, search decision without exception
you can check visible property of form find form showing or closed, :
begin form.show; // load data tthread.createanonymousthread(procedure var i, n : integer; begin // long data loading n := 0; := 0 1000000000 n := n + 1; tthread.synchronize(nil, procedure begin if form.visible form.label1.text := inttostr(n); // add data form end); end).start; end; but not idea, can't stop loading data when form closed. should create tthread class , use it's terminated flag cancel loading of data when form closed, example :
tmythread = class(tthread) public constructor create; protected procedure execute; override; end; ... { tmythread } constructor tmythread.create; begin inherited create(true); freeonterminate := true; end; procedure tmythread.execute; var i, n : integer; stop : boolean; begin n := 0; stop := false; := 1 1000000000 begin if terminated begin stop := true; break; end; n := n + 1; end; if not stop begin synchronize(procedure begin form.label1.text := inttostr(n); end); end; end; show form , start thread :
var mythread : tmythread; { global variable } ... begin form.show; mythread := tmythread.create; mythread.start; end; and terminate thread when form closed :
procedure tform.formclose(sender: tobject; var action: tcloseaction); begin if assigned(mythread) begin mythread.terminate; mythread := nil; end; end;
Comments
Post a Comment