Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / tests / sgen-bridge-gchandle.cs
1 using System;
2 using System.Collections;
3 using System.Threading;
4 using System.Runtime.InteropServices;
5
6
7 public class Bridge {
8         public int __test;
9         public string id;
10         
11         ~Bridge () {
12                 try {Console.WriteLine ("bridge {0} gone", id);} catch (Exception) {}
13         }
14 }
15
16
17 /*
18 Test scenario:
19         Alloc a bridge and create a gc handle to it
20         Get it collected.
21         Create another one and see it steal the handle of the previous one.
22
23
24 */
25 class Driver {
26         public static GCHandle weak_track_handle;
27         public static GCHandle weak_track_handle2;
28
29         static void CreateFirstBridge () {
30                 Bridge b = new Bridge() {
31                         __test = 0,
32                         id = "first",
33                 };
34                 weak_track_handle = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection);
35         }
36
37         static void CreateSecondBridge () {
38                 Bridge b = new Bridge() {
39                         __test = 1,
40                         id = "second",
41                 };
42                 weak_track_handle2 = GCHandle.Alloc (b, GCHandleType.WeakTrackResurrection);
43         }
44
45         static void DumpHandle (GCHandle h, string name) {
46                 Console.WriteLine ("{0}:{1:X} alloc:{2} hasValue:{2}", name, (IntPtr)h, h.IsAllocated, h.Target == null);
47         }
48
49         static int Main () {
50                 var t = new Thread (CreateFirstBridge);
51                 t.Start ();
52                 t.Join ();
53
54                 GC.Collect ();
55                 GC.WaitForPendingFinalizers ();
56                 Console.WriteLine ("GC DONE");
57
58                 DumpHandle (weak_track_handle, "weak-track1");
59
60                 t = new Thread (CreateSecondBridge);
61                 t.Start ();
62                 t.Join ();
63
64                 GC.Collect ();
65                 GC.WaitForPendingFinalizers ();
66                 Console.WriteLine ("GC DONE");
67                 DumpHandle (weak_track_handle, "weak-track1");
68                 DumpHandle (weak_track_handle2, "weak-track2");
69                 Console.WriteLine ("DONE");
70
71                 if ((IntPtr)weak_track_handle == (IntPtr)weak_track_handle2) {
72                         Console.WriteLine ("FIRST HANDLE GOT DEALLOCATED!");
73                         return 1;
74                 }
75
76                 return 0;
77         }
78 }