2004. szeptember 11., szombat
Turn functions and procedures with parameters into threads
Problem/Question/Abstract:
I want to learn how to create and use threads. I have several functions and procedures that are used many times within button click events. The procedures and functions all have at least one parameter (no directives) and one function produces a result (a stringlist). I've spent part of the day reading about threads and how to create them and doing some experimenting. The easiest way seems to be to create a descendant of TThread. But I can't figure out how to handle the parameters.
Answer:
The classic method is this. Pass them to the thread constructor as parameters and, in the constructor, store them in fields of the thread object. When the thread runs, it can use these fields:
myThread = class(TThread)
private
myParam1: integer;
myParam2: integer;
protected
procedure execute; override;
public
constructor create(param1; param2: integer);
end;
myThread.create(param1, param2: integer);
begin
inherited create(true);
myParam1 := param1;
myParam2 := param2;
resume;
end;
If the thread needs a stringList for it's output, create one in the thread, store in the results & post the results back to the main VCL thread.
resultList := TStringList.create;
{ ... }
postMessage(myFormHandle, VCL_MESSSAGE, integer(resultList), 0);
The 'myFormHandle' HWND parameter for the postMessage call will need to be passed in as one of the constructor parameters, as described earlier. VCL_MESSAGE is just some const message number, eg. WM_APP+1000. The form, or whatever component whose handle is passed, will need a message handler procedure to catch the result, but this is fairly well explained in the onLine help:
procedure VCLMESSAGE(var message: TMessage); message VCL_MESSAGE;
{ ... }
procedure myForm.VCLMESSAGE(var message: TMessage);
var
resultList: TStringList;
begin
resultList := TStringList(message.wParam);
end;
Don't forget to free the result stringList after handling it, like I did in my exaple code!
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése