2 using System
.Collections
;
3 using System
.Collections
.Generic
;
4 using System
.Threading
;
5 using System
.Runtime
.InteropServices
;
7 public class Toggleref
{
10 public List
<object> link
= new List
<object> ();
11 public const int DROP
= 0;
12 public const int STRONG
= 1;
13 public const int WEAK
= 2;
20 [StructLayout (LayoutKind
.Explicit
)]
21 public struct Helper
{
26 public static IntPtr
ObjToPtr (object obj
)
28 Helper h
= default (Helper
);
35 static WeakReference
<Toggleref
> root
, child
;
37 [DllImport ("__Internal", EntryPoint
="mono_gc_toggleref_add")]
38 static extern int mono_gc_toggleref_add (IntPtr ptr
, bool strong_ref
);
40 static void Register (object obj
)
42 mono_gc_toggleref_add (Helper
.ObjToPtr (obj
), true);
45 static void SetupLinks () {
46 var a
= new Toggleref () { id = "root" }
;
47 var b
= new Toggleref () { id = "child" }
;
49 a
.__test
= Toggleref
.STRONG
;
50 b
.__test
= Toggleref
.WEAK
;
53 root
= new WeakReference
<Toggleref
> (a
, false);
54 child
= new WeakReference
<Toggleref
> (b
, false);
57 static Toggleref a
, b
;
62 var t
= new Thread (SetupLinks
);
67 GC
.WaitForPendingFinalizers ();
69 Console
.WriteLine ("try get A {0}", root
.TryGetTarget (out a
));
70 Console
.WriteLine ("try get B {0}", child
.TryGetTarget (out b
));
71 Console
.WriteLine ("a is null {0}", a
== null);
72 Console
.WriteLine ("b is null {0}", b
== null);
73 if (a
== null || b
== null)
75 Console
.WriteLine ("a test {0}", a
.__test
);
76 Console
.WriteLine ("b test {0}", b
.__test
);
78 //now we break the link and switch b to strong
80 b
.__test
= Toggleref
.STRONG
;
84 GC
.WaitForPendingFinalizers ();
86 Console
.WriteLine ("try get A {0}", root
.TryGetTarget (out a
));
87 Console
.WriteLine ("try get B {0}", child
.TryGetTarget (out b
));
88 Console
.WriteLine ("a is null {0}", a
== null);
89 Console
.WriteLine ("b is null {0}", b
== null);
90 if (a
== null || b
== null)
92 Console
.WriteLine ("a test {0}", a
.__test
);
93 Console
.WriteLine ("b test {0}", b
.__test
);