Belirtildiği gibi, GUI'yi güncelleştirmek için bir iş parçacığı oluşturmak iyi bir tasarım değil . Konularınızın gerçek bir iş yapmasını sağlamak ve ana iş parçasının ekranınızı güncellemesine izin vermek daha iyi olur.
Delphi ayrıca, iş parçacığı oluşturmayı/yönetmeyi kolaylaştırmak için TThread sınıfını sunarken, aynı zamanda basit iş parçacıklarını yürütmek için Delphi'nin BeginThread
işlevini kullanmayı da isteyebilirsiniz.
// 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.
Burada da parametreler (BeginThread kullanarak) ile konuları nasıl kullanılacağına dair another example: Ben burada yeniden üretmiş bir example on the Delphi Basics web sitesi bulunmaktadır. Tahmin edebiliyorum
Neden niçin bir notta metin koymak için bir iş parçacığı istersiniz? Aslında bu, akla gelebilecek en kötü örnekle ilgilidir, çünkü UI kodunun ana iş parçasında çalışması gerekir. –
@David - durumu kullanıcıya bildirme gibi şeyler için yararlıdır. Yani bir iş parçacığı, diski, kötü amaçlı yazılım için arar. Ana iş parçacığına geri dönüş, "vurur" vb. Senkronize etmek için muhtemelen bunu yapmak gerekir. –
@Chris Oldukça ağır olan 'Synchronize'den kaçınmam ve problemi farklı çözme eğilimindeyim. –