To clean up after your thread finishes executing
- Centralize the cleanup code by placing it in the OnTerminate event handler. This ensures that the code gets executed.
- Do not use any thread-local variables, because OnTerminate is not run as part of your thread.
- You can safely access any objects from the OnTerminate handler.