Newsgroups : Borland : borland.public.delphi.internet.winsock : 2006 May : Re: Best way to shut down server app

www.cryer.info
Managed Newsgroup Archive

Re: Best way to shut down server app

Subject:Re: Best way to shut down server app
Posted by:"Remy Lebeau (TeamB)" (no.spam@no.spam.com)
Date:Fri, 19 May 2006 10:52:31

"John Carlyle-Clarke" <jpcc@removethis.bigfoot.com> wrote in message
news:Xns97C899A172F89discombobulation@207.105.83.66...

> I'm looking for the best way to close down connections
> and the application in an orderly way.

Simply deactivate the server via its Active property.  It will automatically
disconnect any active clients.

> The user closes the form for a connection.  Currently I call:
>
> FContext.Connection.IOHandler.Close;

That is not the correct thing to do.  You should be calling Disconnect()
instead:

    FContext.Connection.Disconnect;

Or

    FContext.Connection.Disconnect(False);

> The user closes the main form.  If I just set
>
> IdTCPServer1.Active := false;
>
> then will each connection raise a Disconnect event?

Yes.  The server's OnDisconnect event is triggered when the internal worker
thread for the socket is being terminated.  Setting the Active property to
False disconnects all active sockets and terminates the threads.

> If so, will this happen synchronously or asynchronously?

Asynchronously.

> If the latter, how do I reliably wait for this to complete?

The Active property already does that for you.  It waits for all threads to
finish being terminated before it then exits.

The only thing you have to watch out for is calling TThread.Synchronize() in
the context of the server's event handlers while you are setting the Active
property in the context of the main thread.  You will deadlock your code if
you call Synchronize() while the server is being shut down, because
Synchronize() cannot be processed while the main thread is blocked on the
Active property.  The threads will be blocked waiting for the Active
property to release the main thread, and the Active property will be blocked
waiting for the threads to terminate.

> Alternatively, I could, from the GUI thread, call
>
> FContext.Connection.IOHandler.Close;
>
> on each connection.

You do not need to do that.  That is already done automatically.

> How can I be sure that all connections are closed before allowing
> the application to exit?

The Active property is blocked while it is shutting everything down.  You
don't have to do anything.

> I seem to get some access violations sometimes on shutdown
> when closing the main form

Your code is likely not thread-safe.  TIdTCPServer is multi-threaded, and
the VCL (especially GUI components) cannot safely be used outside of the
main thread.


Gambit

Replies:

In response to:

www.cryer.info
Managed Newsgroup Archive