Skip to content

Size of WinForms with PublishAot #9911

Open

Description

@MichalStrehovsky

I had a look at the size of WinForms app with PublishAot. I think there's a potential to make the size of AOT-compiled self-contained WinForms apps very attractive (single-digit MB range, fully self-contained).

If I add <PublishAot>true</PublishAot> and <_SuppressWinFormsTrimError>true</_SuppressWinFormsTrimError> to a WinForms default template and dotnet publish it I get a 54 MB executable. One might say “still better than Electron” and call it good, but it can actually be much better.

Drilling into the size with Sizoscope one can immediately see something that should not be there: PresentationFramework.

image

Half of WPF gets dragged in because WinForms started using a WPF interface: ICommand. And ICommand has a bunch of custom attributes on it that drag in WPF.

We can avoid dragging in WPF if we can make sure the string within the custom attribute doesn't actually resolve. One can hack around it by putting this in the csproj for example:

  <Target Name="RemoveWPFReference" BeforeTargets="WriteIlcRspFileForCompilation">
    <ItemGroup>
      <IlcReference Remove="@(IlcReference)" Condition="'%(Filename)' == 'PresentationFramework'" />
    </ItemGroup>
  </Target>

We cannot ship this hack. The only way I can currently think of to fix this would be to divorce WPF and WinForms and stop putting them into the same NuGet/SDK.

With this out of the way, the size of the executable drops to 25.5 MB. We can do better. One thing that Sizoscope will point out is networking stack. It gets brought in from two places – PictureBox and XML. We already have feature switches in place for both PictureBox and XML.
Add this to the csproj to disable these:

<PropertyGroup>
  <XmlResolverIsNetworkingEnabledByDefault>false</XmlResolverIsNetworkingEnabledByDefault>
</PropertyGroup>
  <ItemGroup>
  <!-- We really should introduce a first class property for this -->
    <RuntimeHostConfigurationOption Include="System.Windows.Forms.PictureBox.UseWebRequest" Value="false" Trim="true" />
  </ItemGroup>

With this, the size drops to 21.7 MB.

Looking at what's left in Sizoscope, designers stand out. There's many types that come out of DesignerAttribute and EditorAttribute. Can we make a feature switch to strip them? I experimentally stripped them out and the size drops to 15.2 MB. (Tracked in dotnet/runtime#92043)

A thing that Sizoscope currently doesn't show is manifest resources. Out of the 15.2 MB above, 7.5 MB are embedded resources. They currently cannot be trimmed automatically. Clicking through the manifest resources in WinForms assemblies that are part of the application based on Sizoscope, I see that most (all?) are designer related. Can we get rid of them? If so, the size would drop to ~7 MB.

I think there would be potential to shrink this further (e.g. the TypeConverter on TableLayoutSetting+StyleConverter brings in the entire XML stack with DtdParser and everything), but 7 MB for a fully self-contained WinForms app is already quite encouraging.

Activity

  1. hamarb123 commented on Sep 14, 2023

    @hamarb123
    Contributor

    Also worth noting that including PresentationCore (see here), causes a visible behaviour change, since the DPI to be forced to SystemAware for all WinForms apps which don't declare it in the manifest, even if they set it in Main to something else, if they don't declare [DisableDpiAwareness] (this happens since the module initialiser runs earlier on NAOT, this sort of stuff shouldn't even be in a module initialiser imo). This is not ideal, so we should avoid including Wpf for any WinForms apps, that don't actually use Wpf.

  2. elachlan commented on Sep 14, 2023

    @elachlan
    Contributor

    @JeremyKuhne and @lonitra are the wizards focusing on Winforms AOT for .NET9

    Is the issue with the design attributes because they live in the design assembly? So it pulls in the whole thing?

  3. self-assigned this
    on Sep 14, 2023
  4. added this to the .NET 9.0 milestone on Sep 14, 2023
  5. JeremyKuhne commented on Sep 14, 2023

    @JeremyKuhne
    Member

    Thanks for the details @MichalStrehovsky!

    ICommand has a bunch of custom attributes on it that drag in WPF.

    I had no idea the strings would resolve during compilation. Do you know precisely how this happens? Maybe we could get a feature that is more granular that would allow us to ignore specific usages wherever this is being figured out?

    Note that we're currently focused on getting the key COM pieces converted to ComWrappers so that Accessibility and OLE (clipboard/dragdrop in particular) will work in this scenario. All and any suggestions and help in the AOT/Trimming space are very much appreciated.

    @lonitra

  6. MichalStrehovsky commented on Sep 14, 2023

    @MichalStrehovsky
    MemberAuthor

    I had no idea the strings would resolve during compilation. Do you know precisely how this happens? Maybe we could get a feature that is more granular that would allow us to ignore specific usages wherever this is being figured out?

    The reason why this happens is that the attributes have an annotation instructing trimming to keep things on the types:

    [TypeConverter("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
    public interface ICommand
    {
    }
    
    public sealed class TypeConverterAttribute : Attribute
    {
        public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName) { }
    }

    The annotation on the TypeConverterAttribute constructor instructs trimming to resolve the string and keep the constructor. The constructor brings a massive closure of WPF with it.

    We could ask trimming to drop all TypeConverters, but I assume WinForms actually use type converter and do require this trimming behavior. It just might not be desirable here.

    Cc @vitek-karas @sbomer for ideas

  7. MichalStrehovsky commented on Sep 14, 2023

    @MichalStrehovsky
    MemberAuthor

    Is the issue with the design attributes because they live in the design assembly? So it pulls in the whole thing?

    We don't pull in whole assemblies (unless something forces it, like setting <TrimMode>partial</TrimMode> in the project, or something like that). The designers get pulled in for each individual control that has designer attributes on it.

    The Sizoscope tool is really good at showing the paths to roots for these, try it - it's a WinForms app.

  8. vitek-karas commented on Sep 14, 2023

    @vitek-karas
    Member

    For the designer related attributes: If we can make an assumption that these attributes are not useful when running the app, then there are ways to remove all of those attributes (and what they depend on along with them).
    Similarly for the resources - if there are embedded resources which are there solely for designers and we can say with confidence that they're not going to be needed by the app, we can also remove them. It's just that currently none of this is automatic because the trimmer tools are not smart enough to figure out if these things are actually used by the app or not (for some of these it's really difficult to do even in theory).

    For the type converter: I can't think of a way to solve this super cleanly. There is a direct dependency all the way to all of the WPF functionality. Typically, the only way we can break such a chain is through feature switches - similar to what Michal used to get rid of the networking stack. But that depends on usability - if the code dependency is there, but in reality almost no WinForms app actually runs that code, then maybe a feature switch would be a solution.

    I fear TypeConverter as I know that it's used a lot in WinForms - and it's not very trimming friendly.

  9. elachlan commented on Sep 14, 2023

    @elachlan
    Contributor

    There are some apps that use the designers at runtime. So it would have to be behind a switch, unless the team decided that designers are not supported in AOT scenarios.

    Could CommandConverter live in a different assembly that would avoid PresentationFramework? I know its a breaking change, but it seems like structuring dependencies properly helps with trimming? Please correct me if I am wrong, I am still learning AOT/Trimming.

  10. MichalStrehovsky commented on Sep 14, 2023

    @MichalStrehovsky
    MemberAuthor

    Could CommandConverter live in a different assembly that would avoid PresentationFramework?

    It's not about what assembly CommandConverter lives in. It's about what it's constructor depends on.

    Clicking through the dependency graph in Sizoscope might help building intuition around this. Here I double clicked why the Grid constructor (WPF Grid) is included in an empty WinForms app template.

    It doesn't even fit in a single screen so this is just a part.

    But basically CommandConverter implements ConvertFrom virtual method and since that one is called, we need ConvertFromHelper, that calls GetKnownCommand,... then suddenly we need XamlReader and that has built in support for a bunch of controls.

    image

  11. KlausLoeffelmann commented on Sep 16, 2023

    @KlausLoeffelmann
    Member

    ICommand doesn't live in presentationframework, and we're not using presentationframework currently from the runtime in the context of DataBinding.

    image

    But yes, the attributes are there, but we're actually not using them in the runtime context (and also not in the Designer context, because those would not work, anyway.)

    But apart from that: We will be enabling the ElemenHost at one point, and then at the latest, we would need to have the reference to presentationframework, anyway.

  12. KlausLoeffelmann commented on Sep 16, 2023

    @KlausLoeffelmann
    Member

    I am wondering, how the other UI stacks do that. I mean, the whole ViewModel concept is based on ICommand, and they all use that ICommand, don't they? ICommand is even .NET Standard 1.0 compatible, is it not?

    image

  13. MichalStrehovsky commented on Sep 17, 2023

    @MichalStrehovsky
    MemberAuthor

    I am wondering, how the other UI stacks do that

    The custom attribute is harmless if the project being built doesn't provide a way to resolve the PresentationFramework assembly. WinForms is inflicting it on itself by being packaged together with WPF. Granted it would be better if the ICommand interface wasn't annotated in a way that violated layering/separation of concerns but I don't know if anything can be done about that

  14. 25 remaining items

  15. RussKie commented on May 13, 2024

    @RussKie
    Contributor

    Then there's probably a bunch of other opportunities - I see a lot of WinForms code related to MDI, but many apps don't use MDI so it looks unnecessary. Etc. Sizoscope would let you see all that.

    You'd be surprised how many LOB apps do actually use MDI.

  16. elachlan commented on May 13, 2024

    @elachlan
    Contributor

    All the apps I am maintaining are MDI.

  17. hamarb123 commented on May 13, 2024

    @hamarb123
    Contributor

    I have never used MDI, so it would be a waste of space for me :)

  18. hamarb123 commented on May 13, 2024

    @hamarb123
    Contributor

    wow, I just checked, its like a 90% reduction in file size by using PNG and still having multiple icons. Down to 2.59kb from 53kb on alignment.icon.

    Yeah, if we run all the icons through gimp (iirc I used gimp anyway) we could probably get them smaller. I got an icon down from 416kB to 3kB by using it (which ended up saving me ~1.6MB overall as it was used in multiple places), and still had all the scales I had.

  19. MichalStrehovsky commented on May 13, 2024

    @MichalStrehovsky
    MemberAuthor

    Literally all I said is "many apps don't use MDI so it looks unnecessary". Especially in a WinForms hello world. It amounts to 300 kB of garbage in the WinForms hello world app. It would also be garbage in tools like Sizoscope that also use WinForms, but don't use MDI.

    A quick hack I tried:

    Add a file named ILLink.Substitutions.xml next to the csproj. This is the contents:

    <linker>
      <assembly fullname="System.Windows.Forms">
        <type fullname="System.Windows.Forms.Form">
          <method signature="System.Void UpdateMdiWindowListStrip()" body="stub" />
        </type>
      </assembly>
    </linker>

    Then add this to the csproj:

      <ItemGroup>
        <IlcArg Include="--substitution:ILLink.Substitutions.xml" />
      </ItemGroup>

    Et voilà, 300 kB of garbage removed.

  20. paul1956 commented on May 13, 2024

    @paul1956
    Contributor

    I have very old apps that use MDI and newer ones that don’t. I would love to just see a switch somewhere where I could specify if I need it. My biggest concern is is WebView 2 which is larger than my whole application just to display a Captcha.

  21. MichalStrehovsky commented on May 13, 2024

    @MichalStrehovsky
    MemberAuthor

    I have very old apps that use MDI and newer ones that don’t. I would love to just see a switch somewhere where I could specify if I need it. My biggest concern is is WebView 2 which is larger than my whole application just to display a Captcha.

    I think it's feasible to just restructure code within WinForms so that this can be trimmed naturally. It just currently can't because UpdateMdiWindowListStrip is statically called from Form.OnVisibleChanged and that one is obviously needed. So UpdateMdiWindowListStrip cannot be trimmed and neither can anything that it calls to. The low tech "fix" for situations like this is to realize that for something to become part of MDI, some other method needs to be called first (setter for MdiParentInternal?). So one could replace the static call to UpdateMdiWindowListStrip in OnVisibleChanged to an indirect call (e.g. delegate invocation) and only create the delegate in the other method that actually deals with MDI. That way if nobody calls the method to make the form an MDI form, the delegate will always be null and whatever it would point to gets trimmed. But if MDI is actually used, the delegate will be created and the callback called. There are probably other ways to achieve this, but this is the gist - get rid of the direct calls that cannot be trimmed by setting up an indirection.

    This is just one example. A person more familiar with WinForms will probably find more low hanging fruit than just MDI. This is literally a quick sample I found after messing with this for 15 minutes with little WinForms experience.

  22. elachlan commented on May 30, 2024

    @elachlan
    Contributor

    @MichalStrehovsky raised a good point in this comment:
    #11375 (comment)

    Which is essentially, are all icon/image embedded resources needed for an application compiled AOT?
    If the images loaded by ToolboxBitmapAttribute are only used in the designer, then could we technically trim them when compiling to AOT?

    The other suggestion is to move the icon resources to System.Windows.Forms.Design but again, this depends on if they are only used in the designer. It also makes it harder to just pass the type to ToolboxBitmapAttribute.

  23. elachlan commented on May 31, 2024

    @elachlan
    Contributor

    @MichalStrehovsky I had a chat to the team today and they are very interested in a way to trim out the icons. Is there someone who is more familiar with the trimmer that could help here?

    They are unlikely to accept the PR for the png icons due to backwards compatibility. If we can reduce the risk of breakages then they are more likely to take it on. So adjusting System.Drawing.Bitmap to support png based ico files could help with that. Failing that, bitmap based icons would work with only small size savings.

  24. NCLnclNCL commented on Jun 27, 2024

    @NCLnclNCL

    have this

        <RuntimeHostConfigurationOption Include="System.ComponentModel.Design.IDesignerHost.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.Binding.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.ComponentModel.DefaultValueAttribute.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Drawing.Design.UITypeEditor.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.ActiveXImpl.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.Control.AreDesignTimeFeaturesSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.MdiWindowDialog.IsSupported"
                                        Value="false"
                                        Trim="true" />
         <RuntimeHostConfigurationOption Include="System.Windows.Forms.ImageIndexConverter.IsSupported"
                                        Value="false"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.Primitives.TypeConverterHelper.UseComponentModelRegisteredTypes"
                                        Value="true"
                                        Trim="true" />
        <RuntimeHostConfigurationOption Include="System.Windows.Forms.Control.UseComponentModelRegisteredTypes"
                                        Value="true"
                                        Trim="true" />
      </ItemGroup>
    
  25. NCLnclNCL commented on Jul 1, 2024

    @NCLnclNCL
    <ItemGroup>
      <TrimmableAssembly Include="System.Windows.Forms" />
      <TrimmableAssembly Include="System.Windows.Forms.Primitives" />
    </ItemGroup>
    
    <Target Name="ConfigureTrimming" BeforeTargets="PrepareForILLink">
      <ItemGroup>
        <ManagedAssemblyToLink Condition="'%(Filename)' == 'System.Windows.Forms'">
          <IsTrimmable>true</IsTrimmable>
        </ManagedAssemblyToLink>
        <ManagedAssemblyToLink Condition="'%(Filename)' == 'System.Windows.Forms.Primitives'">
          <IsTrimmable>true</IsTrimmable>
        </ManagedAssemblyToLink>
      </ItemGroup>
    </Target>
    
  26. marked Application size #13945 as a duplicate of this issue on Oct 14, 2025
  27. elachlan commented on Oct 14, 2025

    @elachlan
    Contributor

    This was brought up again in #13945

    There is additional context there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions