1

I have an application that caches several codefluent objects.When I put several of those cached objects in a temporary collection the collection is never released from memory. By profiling the application with ANTS I found the villan: an eventhandler that is attached when the object is inserted in the collection in the 'BaseAdd' function of the collection.

            cwProperty.KeyChanged += new System.EventHandler<CodeFluent.Runtime.Utilities.KeyChangedEventArgs<System.Guid>>(this.OnItemKeyChanged);

How can I prevent this eventhandler to be attached or how can I clean this up?

Peter de Bruijn
  • 792
  • 6
  • 22

2 Answers2

1

The default collection type for an entity is ListCollection. Thus the generated collection store the data in a list and a dictionary. This allows to access an item by its index or its key. When you add an item in this collection, the collection needs to register the KeyChanged event so it can update the dictionary when needed. When you remove an element from the collection, the event is detached.

If you never access items using their key, you can change the collection type to List. Thus, there is no dictionary so no need to register the KeyChanged event.

<cf:entity name="Customer" setType="List">
  <cf:property name="Id" />
  <cf:property name="FullName" />
</cf:entity>
meziantou
  • 20,589
  • 7
  • 64
  • 83
  • I thought of that already but the problem is that the collection is needed in an interface that uses the codefluent collection. I now resolved the issue by removing the subscriptions on the eventhandler. See update... – Peter de Bruijn Jul 13 '16 at 08:22
0

I solved the issue by removing the eventhandler subscriptions since I know the collection is never updated. The OnItemKeyChanged is private thus I made a public function that can be called.

    public void RemoveOnItemKeyChangedHandlers()
    {
        foreach (var cwEntity in this)
        {
            cwEntity.KeyChanged -= new System.EventHandler<CodeFluent.Runtime.Utilities.KeyChangedEventArgs<System.Guid>>(this.OnItemKeyChanged);
        }
    }

While the solution above worked, I eventually changed all items that I cache to Lists in stead of ListCollections. The chance of someone forgetting this issue and creating another memory leak was to big.

Peter de Bruijn
  • 792
  • 6
  • 22