Recent

Author Topic: [SOLVED] Free the Sender  (Read 2331 times)

lainz

  • Hero Member
  • *****
  • Posts: 4743
  • Web, Desktop & Android developer
    • https://lainz.github.io/
[SOLVED] Free the Sender
« on: November 29, 2018, 12:08:22 am »
Hi, I need to free the sender!

btn1.OnClick :=@OnClick;

...OnClick(Sender: TObject)

if bool1 then
  Sender.Free;

But this sometimes causes an exception, there's a safe way to do this? Thanks.
« Last Edit: November 29, 2018, 08:34:48 pm by lainz »

wp

  • Hero Member
  • *****
  • Posts: 13586
Re: Free the Sender
« Reply #1 on: November 29, 2018, 12:30:13 am »
You cannot destroy the Sender by calling Free in the event handler because the rest of the routine is normally processed and will crash if the sender is needed but does not exist any more. Instead, put the request to delete the Sender into the message loop of the application, i.e. use Application.QueueAsyncCall. Then the Free will be handled after the OnClick processing has finished.

This works
Code: Pascal  [Select][+][-]
  1. procedure TForm1.AsyncFree(AData: PtrInt);
  2. begin
  3.   TObject(AData).Free;
  4. end;
  5.  
  6. procedure TForm1.Button1Click(Sender: TObject);
  7. begin
  8.   Application.QueueAsyncCall(@AsyncFree, PtrInt(Sender));
  9. end;

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 12437
  • Debugger - SynEdit - and more
    • wiki

lainz

  • Hero Member
  • *****
  • Posts: 4743
  • Web, Desktop & Android developer
    • https://lainz.github.io/
Re: Free the Sender
« Reply #3 on: November 29, 2018, 08:34:37 pm »
Thanks, it works fine =)

 

TinyPortal © 2005-2018