Anonymous Threads: Use or Lose?

Anonymous threads are simple to use and are highly appealing when you need to quickly put and execute some small piece of code in a background thread.

They work great when they run and complete, but if you have such a thread running when you close the application, all hell can break loose.

The main cause of trouble with anonymous threads is self-destruction on completion. Because of that you cannot store a reference to such a thread and therefore you cannot wait for its completion during application shutdown. Other custom threads which have the FreeOnTerminate flag set to True also suffer from the same problem.

During application shutdown, such self-destroying threads will keep running until they are just killed by the OS, because their owning process exited. This means they can be interrupted at any point during their execution, and they can access shared data long after that data has been destroyed during shutdown.

If you want to avoid unexpected behavior and crashes during application shutdown, then you will have to stop using self-destroying threads. However, if you have a lot of such self-destroying threads, and changing your code and logic would be just too much, there is a quick and dirty trick that can help you to indirectly wait on their completion at shutdown.

You can head to my answer on Stack Overflow to find out how:

You can read more about thread safety in my new book: Delphi Thread Safety Patterns 


Popular posts from this blog

Are generics slow?

Just released book: Delphi Thread Safety Patterns

NX Horizon - Event Bus for Delphi