请记住VCL的访问只能在主线程中,可以使用Synchronize可以让线程的一些方法在主线程中执行。
一个简单使用Synchronize的例子:
Unit ThreadTest;
interface;
uses
classes,SysUtils;
type
TThreadTest=class(TThread)
private
Answer:integer;
protected
procedure GiveAnswer;
procedure Execute;override;
end;
implementation
uses Main;
{TThreadTest}
procedure TThreadTest.GiveAnswer;
begin
MainForm.Edit1.text:=inttostr(Answer);
end;
procedure TThreadTest.Execute;
var
i:integer;
begin
FreeOnTerminate:=True;
For i:=1 to 2000000do
begin
if Terminated then
Break;
Inc(Answer,Round(Abs(Sin(Sqrt(i)))));
Synchronize(GiveAnswer);//注意这里,并注意GiveAnswer函数。
end;
end;
end.
Private Sub btnthread_getdata(ByVal value As DataTable) Handles objnormal.getdata, objthread.getdata
Dim m = New Threading.ThreadStart(AddressOf dataready)
mydataset = value.Copy
DataGrid1.Invoke(m)
End Sub