Archive for October, 2008

Memory Leak in Visual Studio

Friday, October 31st, 2008

By design there is no Assembly.Unload method in .NET Framework. It is a well known fact discussed in details in CLR via C# by Jeffry Richter. There is round-trip solution: because it is possible to unload AppDomain all assemblies loaded in this domain will be unloaded as well.However there are many cases where this approach will not work. Here is a very trivial example. Suppose that all you need is reflecting over types in some assembly. It appears that by standard means the only way to do so is to load this assembly into main AppDomain. It is because types under System.Reflection namespace (Assembly, Type, MethodInfo) can not be passed through domain boundaries. They are neither [Serializable] nor MarshalByRefObjects.

An interesting thing here is that sometimes there is a strong need to dynamically generate and load assemblies. For example, imagine a usual scenario when developer creates user controls in Visual Studio and places them onto the form. For the form designer to perform this an assembly with controls should be loaded to the memory. What VS does? It simply compiles controls into to temporary lib and loads it. Does it mean that VS has a memory leak? Oh, yes it does! Just look at the following screenshot:

This is Visual Studio under self debugger

You may see compiled library loaded multiple times. Now I know why I should reload VS at least twice a day. . .