When exactly do assemblies load?

So, I'm trying to understand when .NET assemblies are loaded into a .NET process. I read this blog post that did a great job explaining things and confirmed a lot of what I thought I already knew, but also raised in which I think I misunderstood a bit.

Dependent assemblies just in time load at the first mention in the code

I took this as meaning that when and, moreover, if the assembly call was made for the first time, the assembly was loaded into the program. Therefore, if I have a program such as the sample below, where the line in which the instance was created RasDialerwill never be called - I assumed that the assembly DotRaswould never be loaded into the process, and I definitely was wrong about that.

However, if the code is really unavailable, as in my commented section, then the assembly will never load, but it seems that if there is a chance, then the assembly will be downloaded.

Here is my little test application:

static void Main(string[] args)
{
    Console.WriteLine("Before");
    var dictionary = new Dictionary<int, string>();
    PrintAssemblies(); // <- DotRas is loaded here for null check variant

    if (dictionary == null)
    {
        // This line will never execute, but it does not matter
        var dialer = new RasDialer();
    }

    // DotRas will not be loaded if I uncomment this and comment 
    // out the other if statement since it is truly unreachable
    //if (false)
    //{
    //    var dialer = new RasDialer();
    //}

    Console.WriteLine(Environment.NewLine + "After");
    PrintAssemblies();

    Console.ReadLine();
}

public static void PrintAssemblies()
{
    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (var assembly in assemblies)
    {
        Console.WriteLine(assembly.GetName());
    }
}

Is there an easy way to tell when the assembly will be loaded into memory?

In the blog entry that I linked at the top, its dependent assembly is not loaded until after it is called PrintAssemblies(), but for me the dependent assembly is loaded before the call. Thus, it does not seem to be easily predictable.

Do I correctly assume that if there is a chance that the type in the dependent assembly is needed by the JIT compiler, will this lead to the assembly loading?

+3
source share
1 answer

Assemblies are loaded as soon as the method that references your assembly is checked.

, . , , .

, , RasDialer, , Main, .

, (, , ). , , , , .

  void A(object arg0) {
      if (argO == null) {
        ClassFromAssembly1.Call();
        B();
        C();
      }
  }

  void B() {
      ClassFromAssembly2.Call();
  }

  [MethodImpl(MethodImplOptions.NoInlining)]
  void C() {
      ClassFromAssembly3.Call();
  }

A , A Assembly1, , , Assembly2.

Assembly3 , C.

arg0 Assembly1. Assembly2 , ( B). Assembly3 arg0.

+6

All Articles