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;
37 public class WeakReference : ISerializable
40 private bool isLongReference;
41 private GCHandle gcHandle;
43 // Helper method for constructors
44 //Should not be called from any other method.
45 private void AllocateHandle (Object target)
47 if (isLongReference) {
48 gcHandle = GCHandle.Alloc (target, GCHandleType.WeakTrackResurrection);
51 gcHandle = GCHandle.Alloc (target, GCHandleType.Weak);
56 public WeakReference (object target)
57 : this (target, false)
61 public WeakReference (object target, bool trackResurrection)
63 isLongReference = trackResurrection;
64 AllocateHandle (target);
67 protected WeakReference (SerializationInfo info, StreamingContext context)
70 throw new ArgumentNullException ("info");
72 isLongReference = info.GetBoolean ("TrackResurrection");
73 Object target = info.GetValue ("TrackedObject", typeof (System.Object));
75 AllocateHandle (target);
79 public virtual bool IsAlive {
81 //Target property takes care of the exception
82 return (Target != null);
86 public virtual object Target {
88 //Exception is thrown by gcHandle's Target
89 return gcHandle.Target;
93 gcHandle.Target = value;
97 public virtual bool TrackResurrection {
99 return isLongReference;
109 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
112 throw new ArgumentNullException ("info");
114 info.AddValue ("TrackResurrection", TrackResurrection);
117 info.AddValue ("TrackedObject", Target);
118 } catch (Exception) {
119 info.AddValue ("TrackedObject", null);