How to release a Firemonkey control properly, in this case a child form with a parent?

自闭症网瘾萝莉.ら 提交于 2019-12-21 19:42:31

问题


From inside an event handler of the control itself, I would like to delete and free it.

A typical use case for TFmxObject.Release, isn't it? However, it only seems to work under Windows, but not Android, and this method is now deprecated anyway.

I know, doesn't work is not a good problem description, but currently I'm not able to debug it under android. Under Windows, I see that the event handler continues correctly after the .Release and after it finished, my log message inside my controls destructor is executed. Under Android, the application hangs.

When I use .Free instead, it still works under Windows (destructor happens immediately, but the handler doesn't access the control after the free), and in Android there is no visible problem, but the destructor is never called, so I have a leak.

With .DisposeOf the effect is the same as with .Release - Windows ok, Android hangs.

I also tried MyParent.RemoveComponent(MyControl) but it all didn't help.

What else do I have to do to release all references so that ARC can do its work? Or how else?


回答1:


TFmxObject.Release uses TThread.ForceQueue internally, and that's currently broken under Android (see discussion above).

As a workaround, a working cross-platform version for releasing an object from its event handler would be

procedure TForm.CloseBtnClick(Sender: TObject);
begin
  Parent := nil;
  TThread.CreateAnonymousThread(
  procedure
  begin
    TThread.Synchronize(nil,
    procedure
    begin
      Self.DisposeOf;
    end);
  end).Start;
end;

Instead of Synchronize you can also use Queue in above method.

What is important to keep in mind is that you should not keep any other references to the control you are releasing or you may hit the trouble down the road.



来源:https://stackoverflow.com/questions/49159986/how-to-release-a-firemonkey-control-properly-in-this-case-a-child-form-with-a-p

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