-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
AutoReleaseTest.cs
86 lines (75 loc) · 2.55 KB
/
AutoReleaseTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
internal static unsafe class ObjectiveC
{
[DllImport(nameof(ObjectiveC))]
public static extern IntPtr initObject();
[DllImport(nameof(ObjectiveC))]
public static extern void autoreleaseObject(IntPtr art);
[DllImport(nameof(ObjectiveC))]
public static extern int getNumReleaseCalls();
}
public class AutoReleaseTest
{
public static int Main()
{
try
{
ValidateNewManagedThreadAutoRelease();
ValidateThreadPoolAutoRelease();
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
return 100;
}
private static void ValidateNewManagedThreadAutoRelease()
{
Console.WriteLine($"Running {nameof(ValidateNewManagedThreadAutoRelease)}...");
using (AutoResetEvent evt = new AutoResetEvent(false))
{
int numReleaseCalls = ObjectiveC.getNumReleaseCalls();
RunScenario(evt);
// Trigger the GC and wait to clean up the allocated managed Thread instance.
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.Equal(numReleaseCalls + 1, ObjectiveC.getNumReleaseCalls());
}
static void RunScenario(AutoResetEvent evt)
{
IntPtr obj = ObjectiveC.initObject();
var thread = new Thread(_ =>
{
ObjectiveC.autoreleaseObject(obj);
evt.Set();
});
thread.Start();
evt.WaitOne();
thread.Join();
}
}
private static void ValidateThreadPoolAutoRelease()
{
Console.WriteLine($"Running {nameof(ValidateThreadPoolAutoRelease)}...");
using (AutoResetEvent evt = new AutoResetEvent(false))
{
int numReleaseCalls = ObjectiveC.getNumReleaseCalls();
IntPtr obj = ObjectiveC.initObject();
ThreadPool.QueueUserWorkItem(_ =>
{
ObjectiveC.autoreleaseObject(obj);
evt.Set();
});
evt.WaitOne();
// Wait 60 ms after the signal to ensure that the thread has finished the work item and has drained the thread's autorelease pool.
Thread.Sleep(60);
Assert.Equal(numReleaseCalls + 1, ObjectiveC.getNumReleaseCalls());
}
}
}