copied mono-api-diff.cs from mono-2-2 branch so new patch can be applied and history...
[mono.git] / mono / tests / gchandles.cs
1 using System;
2 using System.Runtime.InteropServices;
3
4 public class Test1
5 {
6         public GCHandle self;
7         public static bool fail;
8         public static Test1 instance;
9
10         ~Test1 () {
11                 if (self.Target == null)
12                         fail = true;
13         }
14 }
15
16 public class Test2
17 {
18         public GCHandle self;
19         public static bool fail;
20         public static Test2 instance;
21
22         ~Test2 () {
23                 if (self.Target == null)
24                         fail = true;
25         }
26 }
27
28 public class Tests
29 {
30         public static int Main (String[] args) {
31                 return TestDriver.RunTests (typeof (Tests), args);
32         }
33
34         static void create1 () {
35                 Test1.instance = new Test1 ();
36                 Test1.instance.self = GCHandle.Alloc (Test1.instance, GCHandleType.WeakTrackResurrection);
37                 Test1.instance = null;
38         }
39
40         public static unsafe int test_0_track_resurrection () {
41                 /* The GCHandle should not be cleared before calling the finalizers */
42                 create1 ();
43                 GC.Collect ();
44                 GC.WaitForPendingFinalizers ();
45
46                 // WaitForPendingFinalizers doesn't seem to work ?
47                 System.Threading.Thread.Sleep (100);
48                 /* If the finalizers do not get ran by this time, the test will still succeed */
49                 return Test1.fail ? 1 : 0;
50         }
51
52         static void create2 () {
53                 Test2.instance = new Test2 ();
54                 object o = new object ();
55                 Test2.instance.self = GCHandle.Alloc (o, GCHandleType.WeakTrackResurrection);
56                 Test2.instance.self.Target = Test2.instance;
57                 Test2.instance = null;
58         }
59
60         public static int test_0_track_resurrection_set_target () {
61                 /* Same test but the handle target is set dynamically after it is created */
62                 create2 ();
63                 GC.Collect ();
64                 GC.WaitForPendingFinalizers ();
65
66                 System.Threading.Thread.Sleep (100);
67                 return Test2.fail ? 1 : 0;
68         }
69 }