evilone
evilone

Reputation: 22740

Let stay thread running on form close

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

Answers (2)

David Heffernan
David Heffernan

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

Rob Kennedy
Rob Kennedy

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:

  • Programs only have limited time to stop running if the OS is shutting down or the user is logging out, so you might not have time to wait for synchronization to finish before the OS kills your program.
  • Users might wonder why the program is still running even though they told it to close, so consider showing some UI while synchronization continues.
  • Users might not care about synchronization if they're in a hurry and need the program to stop running immediately, so in that UI, you may wish to offer an "abort sync" command.

Upvotes: 6

Related Questions