Définition de l'objet thread
Remonter à Construction d'une application multithread
Pour définir l’objet thread
- Choisissez Fichier > Nouveau > Autre > Projets Delphi > Fichiers Delphi ou Fichier > Nouveau > Autre > Fichiers C++Builder et double-cliquez sur l'icône Objet thread. Le dialogue Nouvel objet thread s'affiche.
- Entrez un nom de classe, par exemple TMyThread.
- Vous pouvez éventuellement cocher la case Thread nommé et spécifier un nom de thread, par exemple MyThreadName.
Conseil : Le fait d'entrer un nom pour Thread nommé facilite le suivi du thread pendant le débogage.
- Cliquez sur OK.
L'éditeur de code affiche le code squelette pour l'objet thread.
Le code généré pour la nouvelle unité ressemblera à cela si vous avez nommé votre classe thread TMyThread :
unit Unit1;
interface
uses
Classes;
type
TMyThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TMyThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TMyThread }
procedure TMyThread.Execute;
begin
{ Place thread code here }
end;
end.
L'ajout d'un nom pour le thread ajoute un appel de la méthode de classe TThread NameThreadForDebugging à la procédure TThread Execute :
unit Unit1;
interface
uses
Classes;
type
TMyThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TMyThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TMyThread }
procedure TMyThread.Execute;
begin
NameThreadForDebugging('My Cool Thread');
{ Place thread code here }
end;
end.
// Unit1.cpp
#include "Unit3.h"
#pragma package(smart_init)
// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(&UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall mythread::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
__fastcall TMyThread::TMyThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
}
void __fastcall TMyThread::Execute()
{
TThread::NameThreadForDebugging("My Cool Thread");
//---- Place thread code here ----
}