summaryrefslogtreecommitdiff
path: root/tests/src/GC/Features/Pinning/PinningOther/PinnedMultiple.cs
blob: 9a22118bd0bf933a132a4d4cf3057afdd7a1f9af (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// Tests multiple handles for same object


using System;
using System.Runtime.InteropServices;

public class Test
{
    public static int Main()
    {
        int[] arr = new int[1000];
        GCHandle[] arrhandle = new GCHandle[10000]; // array of handles to the same object
        IntPtr[] oldaddress = new IntPtr[10000];        // store old addresses
        IntPtr[] newaddress = new IntPtr[10000];        // store new addresses

        for (int i = 0; i < 10000; i++)
        {
            arrhandle[i] = GCUtil.Alloc(arr, GCHandleType.Pinned);
            oldaddress[i] = GCUtil.AddrOfPinnedObject(arrhandle[i]);
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();

        for (int i = 0; i < 10000; i++)
        {
            newaddress[i] = GCUtil.AddrOfPinnedObject(arrhandle[i]);
        }

        for (int i = 0; i < 10000; i++)
        {
            if (oldaddress[i] != newaddress[i])
            {
                Console.WriteLine("Test failed");
                return 1;
            }
        }

        Console.WriteLine("Test passed");
        return 100;
    }
}