views:

278

answers:

3

Hi

How do I access the 'NameThreadForDebugging' in a delphi Thread in Delphi 2010 ?

type
  TMyThread = class(TThread)
  protected
    procedure Execute; override;
    procedure UpdateCaption;
  end;

implementation

procedure TMyThread.UpdateCaption;
begin
  Form1.Caption := 'Name Thread For Debugging'; 
  // how I get 'TestThread1' displayed in the caption  
end;


procedure TMyThread.Execute;
begin
  NameThreadForDebugging('TestThread1');
  Synchronize(UpdateCaption); 
  Sleep(5000);
end;
A: 

AFAICS Delphi supports settings the name only. You'll have to call some windows API function to get the name.

Giel
+8  A: 

The NameThreadForDebugging function is, as its name suggests, for debugging only. If you want to keep track of the name for other purposes, then reserve a field in the thread object and store the name there. Use that field for naming the thread and for populating your form's caption on demand.

There is no API for retrieving a thread's name because threads don't have names at the API level. NameThreadForDebugging raises a special exception that the IDE recognizes as the "name this thread" exception. It sees the exception (since it's a debugger), makes a note about the thread's name in its own internal debugging data structures, and then allows the application to continue running. The application catches and ignores the exception.

That data transfer is one-way, though. The application can send information to the debugger via an exception, but the debugger can't send data back. And the OS is oblivious to everything. To the OS, it's just like any other exception.

Rob Kennedy
As a little addendum, using this method for thread naming _is_ a convention amongst IDEs. In particular, Visual Studio picks it up as well.
Paul-Jan
See also this blog entry by Chris Hesik: http://blogs.embarcadero.com/chrishesik/2009/10/22/34895
Jeroen Pluimers
A: 

The unit DebugThreadSupport on Code Central example ID: 21893, Named Pipes, shows how to set thread name in older versions of Delphi.

Marcelo Rocha
What you wrote here is true, but it doesn't actually answer the question. Also, the code you've linked to provides a way to name a thread, but it, like the built-in VCL code, doesn't provide a way to fetch the name.
Rob Kennedy