How can I capture variables by anonymous method when using it in OTL?

后端 未结 2 814
广开言路
广开言路 2021-01-18 07:54

What I want to do:

I have a few objects in a genric list. I want to capture each of this object in anonymous method and execute this method as a separate OTL Task.

2条回答
  •  醉梦人生
    2021-01-18 08:31

    Anonymous procedures captures variables rather than values. So you are capturing the variable LObject. Since this is a loop variable, the value of LObject changes. The anonymous procedures evaluate LObject when they execute rather than when the anonymous procedures are created.

    Rather than using an anonymous procedure, I'd probably just use a method of TMyObject. Try writing the code that way and I predict you will find it easier to understand.

    procedure TMyObject.TaskProc(const Task: IOmniTask);
    begin
      Writeln(Format('[Thread %d] Object ID: %d', [Task.UniqueID, Self.ID]));
    end;
    

    The reason for getting 4 lines of output rather than 3 is probably just that WriteLn is not threadsafe. Wrap the call to WriteLn in a lock to clear that up.

提交回复
热议问题