Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one access the 'NameThreadForDebugging' in Delphi 2010

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;
like image 584
Charles Faiga Avatar asked Sep 28 '09 13:09

Charles Faiga


2 Answers

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.

like image 177
Rob Kennedy Avatar answered Oct 20 '22 12:10

Rob Kennedy


To do what you ask, you need to store the Name inside your thread class where you can access it, eg:

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

procedure TMyThread.UpdateCaption;
begin
  Form1.Caption := FName; 
end;

procedure TMyThread.Execute;
begin
  FName := 'TestThread1';
  NameThreadForDebugging(FName);
  Synchronize(UpdateCaption); 
  Sleep(5000);
end;
like image 30
Remy Lebeau Avatar answered Oct 20 '22 13:10

Remy Lebeau