inline var bug with anonymous procedure?

▼魔方 西西 提交于 2021-02-16 13:56:12

问题


with the code below:

Procedure TMyForm.doAction;
begin

    generateToken;
    VAR LToken := generatedToken; // Ltoken is set correctly to xxxxx

    //-----
    TThread.CreateAnonymousThread(
      procedure
      begin

        GetData(LToken); // << here LToken is empty !!

      end).Start;

end;

As you can see, the value of LToken is empty inside the anonymous procedure (so the capture didn't work). if I don't use inline var for LToken then it's work

Procedure TMyForm.doAction;
Var LToken: ansiString;
begin
   ....
end;

Is this a bug or a know limitation ?


回答1:


There was a compiler bug in Delphi 10.3.x and inline variables are not properly captured by anonymous methods.

Inline variables don't work with anonymous methods https://quality.embarcadero.com/browse/RSP-26666

Solution for 10.3.x, as you already mentioned, is to define and use local variable instead of using inline variable.

Another solution would be upgrading to 10.4, where capturing inline variables with anonymous methods has been corrected and now it correctly captures inline variable, so you would be able to use your original code.

However, there is additional bug in compiler in 10.4 related to capturing inline variables. If the variable is managed type (interface reference, string...), it is never automatically released and it leaks memory.

Such variables must be explicitly released at the end of anonymous method that captured them. For instance, assigning nil to interface reference or assigning empty string to string variable...

Memory leak: inline Interfaces captured by anonymous methods are not released https://quality.embarcadero.com/browse/RSP-29564



来源:https://stackoverflow.com/questions/62372257/inline-var-bug-with-anonymous-procedure

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