Where to intercept closing application?

Since my repo is public I figure I should fix a glaring bug, like server crashing when you close it when water is flowing. Water flow runs in a thread and relies on the tile list. The tile list is global defined in its unit and inits and disposes in initialize and finalize.

I thought ViewMain.Stop would be where to clean up and stop everything. So that is where I stop the flow thread and close the connection and tidy up. But the tile list unit’s finalization is getting called first and the tile data is destroyed before the thread using that data is stopped. What is the proper way to intercept closing the application before the finalizations are all called? I don’t see a closequery like vcl. I only see OnInitialization on the TCastleApplication.

(The server is based on the tcpserver for indy in the cge examples)

I looked everywhere, but of course asking the question helped me look in the right place. I found what I want in
Application.MainWindow.OnCloseQuery

OnCloseQuery purpose is mostly to check can we close the window – in case we should e.g. ask the user “you have modified the file X, do you want to save? save and exit / don’t save and exit / cancel”.

So yes, OnCloseQuery is called earlier (before the views are stopped and finalization of units is called) but that’s because, when this is called, it’s not really sure whether we will close the window. And as docs say,

This is not called when you explicitly close the window by calling the Close method.

So it’s not really a good place for “cleanup”. To do cleanup, the Stop method of a view is indeed best, as you mentioned.

If Stop happens too late for you (it is done from finalization of CastleWindow unit, which may happen after finalization of one of your own units) then, before the finalization where you need to have the view stopped, do Application.MainWindow.Container.View := nil. This will stop any pending views, executing their Stop methods. So the Stop of your views will be reliably really always done before the code you want.

CloseQuery works for me. Currently closing via the application X is the only way to close it. If I close it from code, I can insure the proper calls are made. This is the server so not meant to run fullscreen always in a window with an X.