Thursday, 10 July 2008

Win32 thread names in the Delphi IDE

The Delphi help only mentions how to do this using C++, and Google doesn't provide the solution in Pascal easily, so I thought that I'd better publish the solution here. In order to see names for your threads in the Delphi IDE while debugging your Win32 application, call SetCurrentThreadName() in your TThread.Execute method:


procedure SetCurrentThreadName(const Name: string);
type
TThreadNameInfo =
record
RecType: LongWord;
Name: PChar;
ThreadID: LongWord;
Flags: LongWord;
end;
var
info:TThreadNameInfo;
begin
// This code is extremely strange, but it's the documented way of doing it!
info.RecType:=$1000;
info.Name:=PChar(Name);
info.ThreadID:=$FFFFFFFF;
info.Flags:=0;
try
RaiseException($406D1388, 0,
SizeOf(info) div SizeOf(LongWord), PDWord(@info));
except
end;
end;


Let's hope it gets easier to find on Google now.

4 comments:

Ondrej Kelle said...

Also see CC16302: Human readable thread identifiers in debugger

Anonymous said...

Cool ! Thanks a lot.

Olaf Monien said...

btw, exactly that code gets added by Delphi's "New Thread Object" wizard.

I believe that's available since at least Delphi 7 - I never checked the docs though :-)

Mikhail Mokhov said...

Yes, Indy uses a similar code too. Citation from idGlobal.pas:
{$IFDEF MSWINDOWS}
with LThreadNameInfo do begin
RecType := $1000;
Name := PChar(AName);
ThreadID := $FFFFFFFF;
Flags := 0;
end;
try
// This is a wierdo Windows way to pass the info in
RaiseException($406D1388, 0, SizeOf(LThreadNameInfo) div SizeOf(LongWord),
PDWord(@LThreadNameInfo));
except end;
{$ENDIF}