Name your threads, even the ones auto-created by Delphi

Updated: Jun 19, 2020

I haven't heard of too many Delphi developers that insist on naming all threads created in an application, but I think it is good practice. Call me overly pedantic if you must, but the practice certainly has come in handy more than a few times over the years.

Now, there is a limit - I typically don't dig into third party component code to name their threads. I simply haven't had the need to do this (yet.)

Contributing to the issue is the few threads created by Delphi on application startup. There's been a few posts over the years on what each of these threads do, but I'm not as interested as what they do but interested in tagging them as typically "not my problem." I have written a handy utility method that will help. You simply include the unit in your Windows project and the few threads created automatically by Delphi will be named as such.

It's surprisingly simple to do when using the Tool Help Library in the Windows API, which are nicely wrapped in the WinAPI.TlHelp32 unit. The full unit is below, and will also be added in the iaLib Github repository.

Simply put, instead of seeing something like this image below in your debugger Threads window:

You'll now see something like the image below, with the Delphi created threads clearly identified:

Granted, it's not an earth-changing difference, but you'll need to ask yourself "How many times have you wondered what Thread Id 11376 is for?" Now, you may not know all the details on what Delphi is doing with each background thread, but you'll now be able to separate the system-managed threads with the application-managed threads perhaps saving you a few headaches down the road.

The example code heavily follows Microsoft's thread walking documentation. You simply create a snapshot of all threads for the CurrentProcessId and use the Thread32First and Thread32Next methods to process the list.

To name your own TThread descendants, use the TThread.NameThreadForDebugging method. Combine that practice with this unit's functionality, you'll have the Delphi-created threads named, all of your threads named, and then you can ponder on the remaining threads listed in the IDE and perhaps go on a fishing trip to determine their source. (See this StackOverflow question for assistance with that task.) The majority of the time, every item in the Threads list will now be named to make your debugging task just a little bit easier.


1,383 views1 comment