WeakReference and event handling

前端 未结 4 2210
鱼传尺愫
鱼传尺愫 2020-12-14 00:53

Is it a good practice to implement event handling through WeakReference if that event is the only thing holding the reference and that we would need the object to be garbage

4条回答
  •  无人及你
    2020-12-14 01:15

    While what you suggest solves one set of problems (event reference management and memory leak prevention), it is likely to open up a new set of problems.

    One problem I can see is during event handling process if the source object is garbage collected (as it was only held with a weak reference), any code that access the source object will result in null reference exception. You can argue that the event handler should either not access the source object or it must have a strong reference, but it can be argued that this could be a worse problem than the one you are trying to solve in the first place.

提交回复
热议问题