Thread-Objekt definieren
Nach oben zu Multithread-Anwendungen erstellen
So definieren Sie ein Thread-Objekt:
- Wählen Sie Datei > Neu > Weitere > Delphi-Projekte > Delphi-Dateien oder Datei > Neu > Weitere > C++Builder-Dateien, und doppelklicken Sie auf das Symbol Thread-Objekt. Das Dialogfeld Neues Thread-Objekt wird angezeigt.
- Geben Sie einen Klassennamen ein, beispielsweise TMyThread.
- Sie können das Kontrollkästchen Benannter Thread aktivieren und einen Namen für den Thread eingeben (z. B. MyThreadName).
Tipp: Die Eingabe eines Namens für den Thread erleichtert die Überwachung des Threads beim Debuggen.
- Klicken Sie auf OK.
Im Quelltext-Editor wird der Skeleton-Quelltext für das Thread-Objekt angezeigt.
Wenn Sie der Thread-Klasse den Namen TMyThread zugewiesen haben, sieht der für die neue Unit erzeugte Quelltext folgendermaßen aus:
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.
Durch das Hinzufügen eines Namens für den Thread wird der Prozedur TThread Execute ein Aufruf der TThread-Klassenmethode NameThreadForDebugging hinzugefügt:
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 ----
}