0

我想创建一个包含(ao)两个属性 ObjectLinks 和 ObjectBacklinks 的 Tinterfacedobject。Objectlinks 包含对其他对象的接口引用,ObjectBacklinks 包含这些链接的反向

这两个属性都包含 TWeakIntfDictionary = class(TDictionary) Backlinks 属性在 ObjectLinks.ValueNotify 事件中维护

为了确保在释放原始对象时从字典中删除接口引用,需要使用通知算法(与 TFmxObject 使用相同)

怀疑我在创建这么多对同一个接口对象的引用时遇到了各种循环引用问题:(但我似乎无法摆脱这个问题。当从被销毁的对象中调用 FreeNotification 时,一切正常很好,直到它从 FreeNOtification 返回。此时再次调用对象的 .Destroy :-(

 {1 Dictionary of interfaces (using weak references) using Free notification }
  TWeakIntfDictionary = class(TDictionary<int64, IInterface>, IFreeNotificationMonitor)
  protected
    procedure ValueNotify(const Value: IInterface; Action: TCollectionNotification); override;
  public
    procedure FreeNotification(aObject: TObject);
  end;

  implementation

  procedure TWeakIntfDictionary.FreeNotification(aObject: TObject);
  var
    lObj: TPair<int64, IInterface>;
  begin
    //Object is going to be destroyed, remove it from dictionary
    for lObj in Self do
    begin
      if (lObj.Value as TObject).Equals(aObject) then
      begin
        Remove(lObj.Key);
        Break;
      end;
    end;
  end;

  procedure TWeakIntfDictionary.ValueNotify(const Value: IInterface; Action: TCollectionNotification);
  var
    lDestrIntf: IFreeNotificationBehavior;
  begin
      // When a TObject is added to the dictionary, it must support IDestroyNotification
      // This dictionary is than added to the notificationlist of the TObject
    if Supports(Value, IFreeNotificationBehavior, lDestrIntf) then
      case Action of
        cnAdded:      begin
                        lDestrIntf.AddFreeNotify(Self);
                        lDestrIntf._Release;
                      end;
        cnRemoved,
        cnExtracted:  begin
                        lDestrIntf.RemoveFreeNotify(Self);
                      end;
      end
    else
      raise EWeakInftDictionaryException.Create('Object added to TWeakIntfDictionary does not support IFreeNotificationBehavior');

    inherited;

  end;

有人知道弱引用字典的现有实现吗?任何人有任何建议如何解决这个问题?

4

1 回答 1

0

在以下代码中找到了解决方案

procedure TWeakIntfDictionary.FreeNotification(aObject: TObject);
var
  ...
begin
  //Object is going to be destroyed, remove it from dictionary
  lSavedEvent := FDict.OnValueNotify;
  FDict.OnValueNotify := nil;
  lRemoveList := TList<TKey>.Create;
  try
    for lPair in FDict do
    begin
      pointer(lIntf) := lPair.Value;
      if (lIntf as TObject) = aObject then
        lRemoveList.Add(lPair.Key);
    end;
    pointer(lIntf):=nil; // avoid _release for the last item

    for lKey in lRemoveList do
      FDict.Remove(lKey);

  finally
    FDict.OnValueNotify := lSavedEvent;
    lRemoveList.Free;
  end;
end;
于 2012-10-26T08:09:57.527 回答