2 // System.WeakReference.cs
5 // Ajay kumar Dwivedi (adwiv@yahoo.com)
8 using System.Runtime.Serialization;
9 using System.Runtime.InteropServices;
14 /// Summary description for WeakReference.
17 public class WeakReference : ISerializable
20 private bool isLongReference;
21 private GCHandle gcHandle;
23 // Helper method for constructors
24 //Should not be called from any other method.
25 private void AllocateHandle(Object target)
27 if(this.isLongReference)
29 this.gcHandle = GCHandle.Alloc(target, GCHandleType.WeakTrackResurrection);
33 this.gcHandle = GCHandle.Alloc(target, GCHandleType.Weak);
39 public WeakReference(object target)
44 public WeakReference(object target, bool trackResurrection)
46 this.isLongReference = trackResurrection;
47 AllocateHandle(target);
51 protected WeakReference(SerializationInfo info, StreamingContext context)
54 throw new ArgumentNullException ("info");
56 this.isLongReference = info.GetBoolean("IsLongReference");
57 //TODO: How to load the exact type?
58 //Does that matter? No idea :(
59 Object target = info.GetValue("TargetObject",typeof(System.Object));
61 AllocateHandle(target);
66 public virtual bool IsAlive
70 //Target property takes care of the exception
71 return (Target != null);
75 public virtual object Target
79 //Exception is thrown by gcHandle's Target
80 return this.gcHandle.Target;
84 this.gcHandle.Target = value;
88 public virtual bool TrackResurrection
92 return this.isLongReference;
103 public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
106 throw new ArgumentNullException ("info");
108 info.AddValue("IsLongReference",this.isLongReference);
111 info.AddValue("TargetObject",Target);
115 info.AddValue("TargetObject",null);