Como se ha señalado, crear un hilo para actualizar la GUI no es un buen diseño . Sería mejor que sus hilos hagan un trabajo real y permitan que el hilo principal actualice su pantalla.
Aunque Delphi también ofrece la clase TThread para facilitar la creación/administración de subprocesos, también puede utilizar la función BeginThread
de Delphi para ejecutar subprocesos sencillos. Hay una página web example on the Delphi Basics, que he reproducido aquí:
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
unit Unit1;
interface
uses
Forms, Dialogs, Windows, SysUtils;
type
TMsgRecord = record
thread : Integer;
msg : string[30];
end;
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
end;
var
Form1: TForm1;
Implementation
{$R *.dfm} // Include form definitions
ThreadVar // We must allow each thread its own instances
// of the passed record variable
msgPtr : ^TMsgRecord;
// Private thread procedure to show a string
function ShowMsg(Parameter : Pointer) : Integer;
begin
// Set up a 0 return value
Result := 0;
// Map the pointer to the passed data
// Note that each thread has a separate copy of msgPtr
msgPtr := Parameter;
// Display this message
ShowMessagePos('Thread '+IntToStr(msgPtr.thread)+' '+msgPtr.msg,
200*msgPtr.thread, 100);
// End the thread
EndThread(0);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
id1, id2 : LongWord;
thread1, thread2 : Integer;
msg1, msg2 : TMsgRecord;
begin
// set up our display messages
msg1.thread := 1;
msg1.msg := 'Hello World';
msg2.thread := 2;
msg2.msg := 'Goodbye World';
// Start the first thread running asking for users first name
thread1 := BeginThread(nil,
0,
Addr(ShowMsg),
Addr(msg1),
0,
id1);
// And also ask for the surname
thread2 := BeginThread(nil,
0,
Addr(ShowMsg),
Addr(msg2),
0,
id2);
// Ensure that the threads are only closed when all done
ShowMessagePos('Press this when other dialogs finished.', 200, 300);
// Finally, tidy up by closing the threads
CloseHandle(thread1);
CloseHandle(thread2);
end;
end.
Aquí también es another example de cómo utilizar hilos con los parámetros (utilizando BeginThread).
¿Por qué le gustaría un hilo para poner texto en una nota? De hecho, es casi el peor ejemplo imaginable porque el código UI necesita ejecutarse en el hilo principal. –
@David: es útil para cosas como informar el estado al usuario. es decir, un hilo ejecuta una búsqueda en el disco en busca de malware. Tiene que informar el progreso, "hits", etc., de vuelta al hilo principal. Es probable que necesite hacer eso a través de Sincronizar. –
@Chris Tiendo a evitar 'Sincronizar', que es bastante pesado y resuelve el problema de manera diferente. –