开发者

Does WeakReference have redundant properties?

WeakReference implementation in .NET has an IsAlive Property.

1) Are there any performance/behavio开发者_Go百科r differences between using the IsAlive property or testing whether the Target property is not null?

2) IsAlive is a redundant property?

Thanks.


1) No. Internally, IsAlive is doing almost exactly the same logic as checking target, and seeing if it's null.

2) Somewhat, since checking whether ref.Target != null is pretty much equivelent to ref.IsAlive. However, IsAlive is more expressive, and potentially easier to understand when maintaining the code.


Looking at the source code, there is no difference in behavior between them. obj.IsAlive is simply more convenient and readable then obj.Target != null.


It is not hard to imagine a concurrent garbage-collection system in which holding a reference to an object even momentarily would have a substantial likelihood of causing that object to survive the next GC (under .Net, it has a relatively small likelihood of doing so). Under such a system, using an object's Target property to determine if it was dead could have the annoying side-effect of keeping the object alive longer than necessary. Using the IsAlive property would avoid that risk.

Note that IsAlive can only be used reliably to determine if an object is dead. If it reports that an object is alive, it may or may not be possible to acquire its target.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜