proper way to free FManager with AureliusDataset

Hi

on my form, I have a AureliusDataset component linked to a DBGrid. As such my FManager is declared at the form level during Form.Create() so that I can assign it to AureliusDataset.Manager.

So I assumed the right way to prevent memory leak would be to Free FManager at FormDestroy.

The code is shown below:




procedure TORMDataForm.InitForm(const ATablename: string);
begin
  FTablename              := ATablename;
  FManager                := TObjectManager.Create(Server.Echo.Pool.GetConnection);
  AureliusDataset.Manager := FManager;
  LoadTable;
end;


procedure TORMDataForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
   AureliusDataset.Close;
   Action := caFree;
end;


procedure TORMDataForm.FormDestroy(Sender: TObject);
begin
  if Assigned(FManager) then
  begin
    FManager.Clear;  // <- is it necessary to call this?
    FManager.Free;  // <- cause exception on closing the form
  end;



Question:

1) What does FManager.Clear do? Looking at the source code seems to be doing ObjectList.Free
- if this free the internal objects... then why do we need to loop through the entity list returned from FManager to delete the whole table?

myList := FManager.Find<TCustomer>.List;
for obj in myList do
  FManager.Remove(obj);


** basically I want to do a "DELETE  FROM TABLE_CUSTOMER"

2) when i do a FManager.Free
- I get an exception error (as reported by MadExcept)

Thanks!
L
You don't need to call Clear, just Free is enough. 

Short Answer to solve the problem: Close the dataset before destroying the manager.


Long Answer: the issue here is that the dataset is owned by the form, and when the form is destroyed the dataset is destroyed and part of destroying process is closing the dataset. The problem is that closing the dataset still deals with its internal data, which are the entities managed by the Manager. But FormDestroy event (where manager and entities are being destroyed) is called before the form destroys the dataset. When dataset is closed, it's referencing entities that do not exist anymore. Just make sure that the dataset is closed *before* the  manager and its entities are destroyed.

Wagner R. Landgraf2016-11-29 14:44:49

Thanks Wagner!


I suspected it was a "race" condition in Freeing the components.

Your explanation is clear.

Thanks!