WeakReference with delegate - .NET standard 2.0

  • Thread starter Thread starter NicolasC
  • Start date Start date
N

NicolasC

Guest
Hi all, hope you're all fine and safe!

Considering the following code:


public class BaseItemCollection
{
public delegate void ItemUpdatedEventHandler(BaseItem item, DbDataReader reader);
public static event ItemUpdatedEventHandler OnItemUpdate;
public static void FireItemUpdated(BaseItem item, DbDataReader reader) => OnItemUpdate?.Invoke(item, reader);

public void Update(BaseItem baseItem, DbDataReader reader){...}


}



BaseItemCollection collection = new BaseItemCollection();
BaseItemCollection.OnItemUpdate += collection.Update;

When the object collection is no longer used, the GC cannot collect because of the event subscription OnItemUpdate and that causes memory leak.


After googling that for a long time, the only suitable solution for this seems to be Weak Event patterns. But my problem is I'm working in a class library based on .NET standard 2.0 I cannot upgrade because it must remain compatible with UWP.

I'd like enable the GC to collect collection when there is no reference to it but the event...

Any recommendation about how to deal with that problem?

Thank you in advance for your suggestions.

Continue reading...
 
Back
Top