Small knowledge in the NET class library: weak reference

xiaoxiao2021-03-20  221

1, what is a weak reference? Normally, an instance is quoted by other instances, then he will not be recycled by GC, and weak reference means that if an instance is not referenced by other instances (real reference), but only is weakly referenced, then He will be recycled by GC. 2, the use of weak references. If a class "Class person" is established, he has a "hand". Private class hand _ hand; public class handle {get {return _ hand;}}, in the class hand, I hope to access "Father", it is human, for example, after receiving the burns, immediately notify "Father": People A child object "brain" a message "good pain." At this time, you need to define a "people" attribute in the hand of the class and incur yourself when the Class is initialized. _ 手 = new class hand (); _ hand. Human = this; Because people quoted their hands, while the hand refers to people, if they try to release people, they will first release their hands, but the premise of releasing hands is to release people, this is "cycle reference". Weak reference is to solve this problem, if the person refers to the hand (true reference), but the hand is quoted, so the man is released, and the release will no longer need to release people first. 3. Implementing weak references in .NET In .NET, MS provides weak reference functions at the bottom level, there is a WeakReference class in the System space. Here is the presentation using this class (Note: Using INTERNAL in the set method can only be received in .NET, if you use .NET 1.x, please extract SETParent method) private weakreference _parentReference; / **

/// Returns the parent component of the current component //// public object parent {get {if (_parentReference! = null) {return_parentReference.target;} else {returnes;}}} INTERNAL SET { (value == null) {_parentReference = null;} else {_parentReference = new weakreference (value);}}}

转载请注明原文地址:https://www.9cbs.com/read-130385.html

New Post(0)