Pass parameters to Synchronize procedure call

无人久伴 提交于 2019-12-01 00:46:41

Use anonymous methods.

As you can read in the manual for the TThread.Synchronize

Synchronize(
  procedure
  begin
    Form1.Memo1.Lines.Add('Begin Execution');
  end);

In the example above the referenced variable Form1 would kind of like be copied and saved until the procedure gets executed (that is called variable capture).

Note: David objects to the idea of "copied variable" and he probably is right. However discussing all the corner cases and implementation details would be an overkill. His comparison to "global variable" OTOH would probably have troubles with recursive procedures, etc. All the simple to grasp analogies are very rough and tilted one way or another ISTM.

Your anonymous procedure should use your variables val1 and val2 and they then should get captured too

http://docwiki.embarcadero.com/Libraries/XE5/en/System.Classes.TThread.Synchronize

If you're using an older version of Delphi that doesn't support anonymous methods, you make your "parameters" fields on your class. I.e.

procedure ThreadObject.Execute;
var
  val1,val2:integer;
  Star:string;
begin
  FVal1 := val1;
  FVal2 := val2;
  FStar := Star;
  Synchronize(funcyfunc);
end;

procedure ThreadObject.FuncyFunc;
begin
  //Do stuff with FVal1, FVal2 and FStar
end;

Note these are not global.
It is also quite safe because the point of Synchronize is to ensure that two threads co-ordinate with each other. So, provided you don't have other threads trying to access the same data, you won't have any race conditions.

Yes, it is a little "klunky", but that's the advantage of using anonymous methods in newer versions of Delphi.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!