2 // System.WeakReference.cs
5 // Ajay kumar Dwivedi (adwiv@yahoo.com)
9 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Runtime.Serialization;
32 using System.Runtime.InteropServices;
38 public class WeakReference : ISerializable
41 private bool isLongReference;
42 private GCHandle gcHandle;
44 // Helper method for constructors
45 //Should not be called from any other method.
46 private void AllocateHandle (Object target)
48 if (isLongReference) {
49 gcHandle = GCHandle.Alloc (target, GCHandleType.WeakTrackResurrection);
52 gcHandle = GCHandle.Alloc (target, GCHandleType.Weak);
58 protected WeakReference ()
62 public WeakReference (object target)
63 : this (target, false)
67 public WeakReference (object target, bool trackResurrection)
69 isLongReference = trackResurrection;
70 AllocateHandle (target);
73 protected WeakReference (SerializationInfo info, StreamingContext context)
76 throw new ArgumentNullException ("info");
78 isLongReference = info.GetBoolean ("TrackResurrection");
79 Object target = info.GetValue ("TrackedObject", typeof (System.Object));
81 AllocateHandle (target);
85 public virtual bool IsAlive {
87 //Target property takes care of the exception
88 return (Target != null);
92 public virtual object Target {
94 // This shouldn't throw an exception after finalization
95 // http://blogs.msdn.com/b/yunjin/archive/2005/08/31/458231.aspx
96 if (!gcHandle.IsAllocated)
98 return gcHandle.Target;
102 gcHandle.Target = value;
106 public virtual bool TrackResurrection {
108 return isLongReference;
118 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
121 throw new ArgumentNullException ("info");
123 info.AddValue ("TrackResurrection", TrackResurrection);
126 info.AddValue ("TrackedObject", Target);
127 } catch (Exception) {
128 info.AddValue ("TrackedObject", null);