Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I had this same problem, and solved it like this (WeakDictionary is the class I was trying to clean up):</p> <pre><code>internal class CleanerRef { ~CleanerRef() { if (handle.IsAllocated) handle.Free(); } public CleanerRef(WeakDictionaryCleaner cleaner, WeakDictionary dictionary) { handle = GCHandle.Alloc(cleaner, GCHandleType.WeakTrackResurrection); Dictionary = dictionary; } public bool IsAlive { get {return handle.IsAllocated &amp;&amp; handle.Target != null;} } public object Target { get {return IsAlive ? handle.Target : null;} } GCHandle handle; public WeakDictionary Dictionary; } internal class WeakDictionaryCleaner { public WeakDictionaryCleaner(WeakDictionary dict) { refs.Add(new CleanerRef(this, dict)); } ~WeakDictionaryCleaner() { foreach(var cleanerRef in refs) { if (cleanerRef.Target == this) { cleanerRef.Dictionary.ClearGcedEntries(); refs.Remove(cleanerRef); break; } } } private static readonly List&lt;CleanerRef&gt; refs = new List&lt;CleanerRef&gt;(); } </code></pre> <p>What this two classes try to achieve is to "hook" the GC. You activate this mechanism by creating an instance of WeakDictionaryCleaner during the construction of the weak collection:</p> <pre><code>new WeakDictionaryCleaner(weakDictionary); </code></pre> <p>Notice that I don't create any reference to the new instance, so that the GC will dispose it during the next cycle. In the ClearGcedEntries() method I create a new instance again, so that each GC cycle will have a cleaner to finalize that in turn will execute the collection compaction. You can make the CleanerRef.Dictionary also a weak reference so that it won't hold the dictionary in memory.</p> <p>Hope this helps</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload