开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜