Writing Clean-up Code

From RAD Studio
Jump to: navigation, search

Go Up to Defining thread objects Index

You can centralize the code that cleans up when your thread finishes executing. Just before a thread shuts down, an OnTerminate event occurs. Put any clean-up code in the OnTerminate event handler to ensure that it is always executed, no matter what execution path the Execute method follows.

The OnTerminate event handler is not run as part of your thread. Instead, it is run in the context of the main VCL thread of your application. This has two implications:

  • You can't use any thread-local variables in an OnTerminate event handler (unless you want the main thread values).
  • You can safely access any objects from the OnTerminate event handler without worrying about clashing with other threads.

See Also