C# WeakReference object is NULL in finalizer although still strongly referenced

后端 未结 3 1711
Happy的楠姐
Happy的楠姐 2020-12-17 04:14

Hi I have code here where I don\'t understand why I hit the breakpoint (see comment).

Is this a Microsoft bug of something I don\'t know or I don\'t understand prope

3条回答
  •  无人及你
    2020-12-17 05:00

    A sometimes-irksome limitation of WeakReference is that a WeakReference may be invalidated if no strongly-rooted reference exists to the WeakReference itself, and this may occur even if the trackResurrection constructor parameter was true, and even if the target of the WeakReference is strongly rooted. This behavior stems from the fact that a WeakReference has an unmanaged resource (a GC handle) and if the finalizer for the WeakReference didn't clean up the GC handle, it would never get cleaned up and would constitute a memory leak.

    If it will be necessary for an object's finalizers to make use of WeakReference objects, the object must make some provision to ensure that those objects remain strongly referenced. I'm not sure what the best pattern is to accomplish this, but the ConditionalWeakTable that was added in .net 4.0 may be useful. It's a little bit like Dictionary except that as long as a table itself is strongly referenced and a given key is strongly referenced, its corresponding value will be regarded as strongly referenced. Note that if a ConditionalWeakTable holds an entry linking X to Y, and Y to the table, then as long as X or Y remains, the table will remain as well.

提交回复
热议问题