Pass parameters to Synchronize procedure call

前端 未结 2 500
忘掉有多难
忘掉有多难 2021-01-03 11:37

When creating a thread object, I want to call code from the application that needs to be synchronized. The problem is that I don\'t know how to call Synchronize

2条回答
  •  梦谈多话
    2021-01-03 12:11

    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.

提交回复
热议问题