1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Reflection;
7 using System.Runtime.CompilerServices;
8 using System.Runtime.Loader;
10 class TestAssemblyLoadContext : AssemblyLoadContext
12 public TestAssemblyLoadContext() : base(isCollectible: true)
16 protected override Assembly Load(AssemblyName name)
21 public class Test22888
23 [MethodImpl(MethodImplOptions.NoInlining)]
24 static Stream LoadGetResourceStreamAndUnload(string assemblyPath, out WeakReference alcWeakRef)
26 var alc = new TestAssemblyLoadContext();
27 alcWeakRef = new WeakReference(alc);
29 Assembly a = alc.LoadFromAssemblyPath(assemblyPath);
30 Stream resourceStream = a.GetManifestResourceStream("test22888.resources");
33 return resourceStream;
36 [MethodImpl(MethodImplOptions.NoInlining)]
37 static bool LoadAndUnload(string assemblyPath, out WeakReference alcWeakRef)
39 Stream s = LoadGetResourceStreamAndUnload(assemblyPath, out alcWeakRef);
41 bool success = (s != null);
45 for (int i = 0; alcWeakRef.IsAlive && (i < 10); i++)
48 GC.WaitForPendingFinalizers();
51 // Verify that the ALC is still alive - it should be kept alive by the Stream.
52 success = alcWeakRef.IsAlive;
55 Console.WriteLine("Failed to keep AssemblyLoadContext alive by the resource stream");
61 Console.WriteLine("Failed to get resource stream from the test assembly");
67 public static int Main()
69 string currentAssemblyDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath);
70 string testAssemblyFullPath = Path.Combine(currentAssemblyDirectory, "test22888resources.exe");
72 WeakReference alcWeakRef;
73 bool success = LoadAndUnload(testAssemblyFullPath, out alcWeakRef);
77 for (int i = 0; alcWeakRef.IsAlive && (i < 10); i++)
80 GC.WaitForPendingFinalizers();
83 // Now the ALC should not be alive anymore as the resource stream is gone
84 success = !alcWeakRef.IsAlive;
87 Console.WriteLine("Failed to unload the test assembly");
91 return success ? 100 : 101;