开发者

Referenced assemblies getting loaded regardless of the actual code (execution) path?

开发者 https://www.devze.com 2023-02-16 02:07 出处:网络
Normally referenced assemblies should not be loaded until a specific type from that assembly is used. But here is a the question:

Normally referenced assemblies should not be loaded until a specific type from that assembly is used. But here is a the question:

This is a Winforms application. Although the Presentati开发者_如何学编程onFramework.dll & System.Xaml.dll assemblies are referenced, they should not be loaded as below code path never executes;

bool useAutoHandler = false;

if (useAutoHandler) // This is always false so below code is not executed!
{
    var currentApplication = typeof(System.Windows.Application).GetProperty("Current");
    if (currentApplication != null)
    {
        var application = currentApplication.GetValue(this, null) as System.Windows.Application;
        if (application != null)
        {
            application.DispatcherUnhandledException += this.DispatcherUnhandledException;
        }
    }
}

When I query loaded assemblies with AppDomain.CurrentDomain.GetAssemblies(), I see presentation framework core & xaml being loaded. Any ideas as to why this is the case?


You are loading the PresentationFramework.dll assembly in this very same line: typeof(System.Windows.Application) because you are statically referencing a type contained withing this assembly.

If you compile this in Release Mode the compiler would probably optimize this code and completely remove this if from the resulting IL. If the body of the if statement is part of the resulting IL at runtime when the moment for the method containing this code to be executed comes, the JIT will need to translate it into machine code and because you have statically referenced a type within this assembly it would need to load the corresponding assembly.


Referenced assembly is loading into the process memory before stepping into method where reference is present.

If you change your code into something like this:

private void Foo()
{
  var currentApplication = typeof(System.Windows.Application).GetProperty("Current");
  if (currentApplication != null)
  {
    var application = currentApplication.GetValue(this, null) as    System.Windows.Application;
    if (application != null)
    {
      application.DispatcherUnhandledException += this.DispatcherUnhandledException;
    }
  }
}

public void Bar(bool useAutoHandler)
{
  if (useAutoHandler)
  {
    Foo();
  }
}

then running Bar(false) should not load extra assemblies.

0

精彩评论

暂无评论...
验证码 换一张
取 消