Author: Tomas Rutkauskas
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:
1 myThread = class(TThread)
2 private
3 myParam1: integer;
4 myParam2: integer;
5 protected
6 procedure execute; override;
7 public
8 constructor create(param1; param2: integer);
9 end;
10
11 myThread.create(param1, param2: integer);
12 begin
13 inherited create(true);
14 myParam1 := param1;
15 myParam2 := param2;
16 resume;
17 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.
18
19 resultList := TStringList.create;
20 { ... }
21 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:
22
23 procedure VCLMESSAGE(var message: TMessage); message VCL_MESSAGE;
24 { ... }
25
26 procedure myForm.VCLMESSAGE(var message: TMessage);
27 var
28 resultList: TStringList;
29 begin
30 resultList := TStringList(message.wParam);
31 end;
Don't forget to free the result stringList after handling it, like I did in my exaple code!
|