Reputation: 22740
I made a syncing thread on my application and I want to know is there a way to let the thread stay open until it finishes it's syncing process, if i close the application form?
Upvotes: 2
Views: 1191
Reputation: 612993
In the commentary to Rob's excellent answer, the question of showing UI whilst waiting was raised. If you need to show UI whilst waiting, then you will need a more advanced wait that TThread.WaitFor
. This is what I use in its place, relying on MsgWaitForMultipleObjects
.
procedure WaitUntilSignaled(Handle: THandle; ProcessMessages: Boolean);
begin
if ProcessMessages then begin
Application.ProcessMessages;//in case there are any messages are already waiting in the queue
while MsgWaitForMultipleObjects(1, Handle, False, INFINITE, QS_ALLEVENTS)=WAIT_OBJECT_0+1 do begin
Application.ProcessMessages;
end;
end else begin
WaitForSingleObject(Handle, INFINITE);
end;
end;
....
Form.Show;
WaitUntilSignaled(Thread.Handle, True);
Form.Close;
Upvotes: 1
Reputation: 163287
Call the thread's WaitFor
method in your DPR file, after the Application.Run
line. If the thread has already finished running, then WaitFor
will return immediately. Otherwise, it will pause the main thread until the other thread terminates. (You'll have to make sure the variable still refers to a valid TThread
instance, so don't set its FreeOnTerminate
property.)
There are additional things you may wish to consider, beyond the simple issue of allowing the thread to continue running:
Upvotes: 6