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 ("TrackResurrection");
57 Object target = info.GetValue ("TrackedObject", typeof (System.Object));
59 AllocateHandle(target);
64 public virtual bool IsAlive
68 //Target property takes care of the exception
69 return (Target != null);
73 public virtual object Target
77 //Exception is thrown by gcHandle's Target
78 return this.gcHandle.Target;
82 this.gcHandle.Target = value;
86 public virtual bool TrackResurrection
90 return this.isLongReference;
100 public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
103 throw new ArgumentNullException ("info");
105 info.AddValue ("TrackResurrection", TrackResurrection);
108 info.AddValue ("TrackedObject", Target);
110 info.AddValue("TrackedObject",null);