Skip to content

Improved incremental build/reference assembly support #5458

Open

Description

@rainersigwald

(This was reported to me offline via email; I'm adding some context.)

MSBuild and the Roslyn compilers use a feature called reference assemblies to attempt to minimize the build impact of changes to referenced assemblies. When the internal implementation of an assembly changes without changes to its public API surface, referencing projects shouldn't need to rebuild. This feature is turned on by default for projects targeting .NET 5.0+.

This isn't working for WPF projects, though. As an example, take a small solution with two projects: a library and a WPF app that references the library. Change whitespace in the library and build the solution. Ideally, the library would recompile, the WPF app would not, and the library would just be copied to the output folder of the WPF app.

In the current implementation, the WPF app is always rebuilt. The proximate cause is

Target Name=CoreCompile Project=WpfApp.csproj
    Building target "CoreCompile" completely.
    Output file "obj\Debug\net5.0-windows\WpfApp.dll" does not exist.

That's happening in

Target Name=CleanupTemporaryTargetAssembly Project=WpfApp.csproj
    Task "Message" skipped, due to false condition; ('$(MSBuildTargetsVerbose)'=='true') was evaluated as (''=='true').
    Delete
    Delete
        Parameters
            Files = obj\Debug\net5.0-windows\WpfApp.dll
        Deleting file "obj\Debug\net5.0-windows\WpfApp.dll".
    Delete

That's happening because the _wpftmp project builds to the same location.

The _wpftmp project builds because MarkupCompilePass1 tells it to:

_RequireMCPass2ForMainAssembly = True

It's doing that because it is taking the implementation assembly as an input, through @(ReferencePath).

I think it could use @(ReferencePathWithRefAssemblies) like CoreCompile does.

Activity

  1. rainersigwald commented on Oct 6, 2021

    @rainersigwald
    MemberAuthor

    I think it could use @(ReferencePathWithRefAssemblies) like CoreCompile does.

    I just tried this and it didn't quite work; I still see _RequireMCPass2ForMainAssembly = True. Looks like it'll take a bit more digging into the MarkupCompilePass1 task to figure out why.

  2. rainersigwald commented on Oct 6, 2021

    @rainersigwald
    MemberAuthor

    Great pointer. The reference assemblies feature should make it so that the references passed to the compiler aren't touched. I'll see if I can debug through to see what it thinks has been.

  3. rainersigwald commented on Oct 6, 2021

    @rainersigwald
    MemberAuthor

    Fortunately I think I just hadn't run the scenario I thought I had. Things seem to be working now with this change:

    --- C:\Program Files\dotnet\sdk\5.0.401\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.WinFX.targets
    +++ private modification
    @@ -215,13 +215,13 @@
       ================================================================
                                        MarkupCompilePass1
       ================================================================
       -->
     
       <Target Name="MarkupCompilePass1"
    -          DependsOnTargets="$(MarkupCompilePass1DependsOn);SplashScreenValidation"
    +          DependsOnTargets="$(MarkupCompilePass1DependsOn);SplashScreenValidation;FindReferenceAssembliesForReferences"
               Condition="'@(Page)' != '' or '@(ApplicationDefinition)' != '' " >
     
             <Message Text="(in) Page: '@(Page)'" Condition="'$(MSBuildTargetsVerbose)'=='true'"/>
             <Message Text="(in) ApplicationDefinition: '@(ApplicationDefinition)'" Condition="'$(MSBuildTargetsVerbose)'=='true'"/>
             <Message Text="(in) Resource: '@(Resource)'" Condition="'$(MSBuildTargetsVerbose)'=='true'"/>
             <Message Text="(in) CodeGenReference: '@(ReferencePath)'" Condition="'$(MSBuildTargetsVerbose)'=='true'"/>
    @@ -246,13 +246,13 @@
                    PageMarkup="@(Page)"
                    ContentFiles="@(Content)"
                    AssemblyName="$(AssemblyName)"
                    OutputType="$(OutputType)"
                    AssemblyVersion="$(AssemblyVersion)"
                    AssemblyPublicKeyToken="$(AssemblyPublicKeyToken)"
    -               References="@(ReferencePath)"
    +               References="@(ReferencePathWithRefAssemblies)"
                    RootNamespace="$(RootNamespace)"
                    KnownReferencePaths="$(MSBuildBinPath);$(TargetFrameworkDirectory);@(_TargetFrameworkSDKDirectoryItem);@(KnownReferencePaths)"
                    AssembliesGeneratedDuringBuild="@(AssembliesGeneratedDuringBuild)"
                    AlwaysCompileMarkupFilesInSeparateDomain="$(AlwaysCompileMarkupFilesInSeparateDomain)"
                    HostInBrowser="$(HostInBrowser)"
                    LocalizationDirectivesToLocFile="$(LocalizationDirectivesToLocFile)"

    I think this is too risky for 6.0 GA but it'd be a nice speedup for 6.0.200/VS 17.1 if we could get it . . .

  4. albahari commented on Oct 7, 2021

    @albahari

    This patch works for me and results in a massive improvement to build times.

  5. Yarith commented on May 7, 2022

    @Yarith

    I have written a single targets file, to compile all workarounds so we can have incremental wpf builds now. I can not override the inputs of the MarkupCompilePass1 task, so i will give warnings if the patch is still not applied. Also i have used the workaround from here so the GeneratedInternalTypeHelper.g.cs it is not causing rebuilds. The types used in xaml must now be public, in our codebase this is the case, otherwise the designer will have problems. There were also the problem with the other generated code files. Especially the files that are based on the current project name, which are always random for the temporary project. The already existing files were always overridden, but were ending up with the exact same content. Now there will be a .timestamp file in the obj folder to preserve the last modified timestamps. All of this is the minimum required so the csharp code will not get compiled.

    With all the workarounds i was able to have incremental builds with all our wpf projects. I hope the correct solution to this problem will be integrated in the sdk before those workarounds stop working. Here is the content of the targets file:

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <!-- This targets-File workarounds the issue, that the wpf project is rebuild because
           of changes on project references, even if the ref-Files have not changed.
           1. We will copy the generated files with the .timestamp ending, if the contents have changed.
           Then we copy it back, but only if it has the same contents. The effect is, that we end up with the timestamp
           of some old compilation. This is currently implemented for following files:
             - *.g.cs -> *.g.cs.timestamp
             - *.g.i.cs -> *.g.cs.timestamp
             - [AssemblyName]_kk0nk2cx_wpftmp.AssemblyInfo.cs -> [AssemblyName]_wpftmp.AssemblyInfo.cs.timestamp
             - [AssemblyName]_kk0nk2cx_wpftmp.GlobalUsings.cs -> [AssemblyName]_wpftmp.GlobalUsings.cs.timestamp
           2. The multi pass compilation of wpf projects causes the creation of a random temporary project file. This causes
           a new file for AssemblyInfo und GlobalUsings. The name of our .timestamp file will have the random part removed.
           3. There is a race condition bug in the creation of GeneratedInternalTypeHelper.g.cs, which occurs if you have
           no internal type in your wpf project which gets referenced by xaml files. So you have two options to workaround it.
             - Always reference in one xaml file an internal type. 
               Important: If you take this option, you need to extend the .timestamp logic for each compilation pass.
             - Always exclude the GeneratedInternalTypeHelper.g.cs and never reference in at least one xaml file an internal type.
           Here we have taken the second option, because it is far easier to do. The file is used by the designer, so if it gets
           wanky try to disable it with: <EnableWorkaround2281>false</EnableWorkaround2281>
           4. The MarkupCompilePass1 does not support RefOut-Assemblies yet. As long the SDK does not support incremental wpf builds,
           you are required to apply a patch to a file your self. If it is not done yet, you will get a warning with the instructions
           to apply https://github.com/dotnet/wpf/issues/5458#issuecomment-937165247
           5. Now the incremental build for wpf projects should work.
      -->
      
      <PropertyGroup>
        <!--This is a hack to try and fix https://github.com/Microsoft/msbuild/issues/4217-->
        <MarkupCompilePass1DependsOn>$(MarkupCompilePass1DependsOn);GenerateTargetFrameworkMonikerAttribute</MarkupCompilePass1DependsOn>
        <EnableWorkaround2281 Condition="'$(EnableWorkaround2281)' == ''">true</EnableWorkaround2281>
        <EnableWorkaround5458Check Condition="'$(EnableWorkaround5458Check)' == ''">true</EnableWorkaround5458Check>
        <!-- #5697: Fix RootNamespace in WPF inner builds so they are constant across builds. -->
        <!-- See: https://github.com/dotnet/wpf/issues/5697 -->
        <RootNamespace Condition=" $(RootNamespace.EndsWith('_wpftmp')) ">$(_TargetAssemblyProjectName)</RootNamespace>
      </PropertyGroup>
    
      <UsingTask TaskName="ReplaceIfFileTextChanged" TaskFactory="RoslynCodeTaskFactory"
                 AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
        <ParameterGroup>
          <InputFilename ParameterType="System.String" Required="true" />
          <OutputFilename ParameterType="System.String" Required="true" />
          <IfFileTextSame ParameterType="System.Boolean" />
        </ParameterGroup>
        <Task>
          <Using Namespace="System" />
          <Using Namespace="System.IO" />
          <Code Type="Fragment" Language="cs">
            <![CDATA[
                var inputFilenameSplit = InputFilename.Split(';');
                var outputFilenameSplit = OutputFilename.Split(';');
                var count = Math.Min(inputFilenameSplit.Length, outputFilenameSplit.Length);
                for (int i = 0; i < count; i++)
                {
                    var inputFilename = inputFilenameSplit[i];
                    var outputFilename = outputFilenameSplit[i];
                    if (!System.IO.File.Exists(inputFilename)) 
                        return _Success;
    
                    var inputText = System.IO.File.ReadAllBytes(inputFilename);
                    var outputText = 
                        !System.IO.File.Exists(outputFilename) ? null 
                        : System.IO.File.ReadAllBytes(outputFilename);
                    if ((outputText == null || !inputText.SequenceEqual(outputText)) != IfFileTextSame) 
                    { 
                        System.IO.File.Copy(inputFilename, outputFilename, true); 
                    }
                }
              ]]>
          </Code>
        </Task>
      </UsingTask>
    
    
    
      <!-- Restore Timestamp: *.g.cs;*.g.i.cs -->
      <Target Name="TimestampGeneratedCsForXaml" AfterTargets="MarkupCompilePass1" BeforeTargets="CoreCompile">
        <ItemGroup>
          <TimestampGeneratedCsForXamlItem Include="$(IntermediateOutputPath)\**\*.g.cs"/>
          <TimestampGeneratedCsForXamlItem Include="$(IntermediateOutputPath)\**\*.g.i.cs"/>
        </ItemGroup>
    
        <PropertyGroup>
          <OriginalFileName>@(TimestampGeneratedCsForXamlItem->'%(RelativeDir)%(Filename)%(Extension)')</OriginalFileName>
          <BackupFileName>@(TimestampGeneratedCsForXamlItem->'%(RelativeDir)%(Filename)%(Extension).timestamp')</BackupFileName>
        </PropertyGroup>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(OriginalFileName)"
            OutputFilename="$(BackupFileName)"
            Condition="'$(OriginalFileName)' != ''"/>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(BackupFileName)"
            OutputFilename="$(OriginalFileName)"
            IfFileTextSame="true"
            Condition="'$(OriginalFileName)' != ''"/>
      </Target>
    
      <!-- Restore Timestamp: *.baml -->
      <Target Name="TimestampGeneratedBamlForXaml" AfterTargets="MarkupCompilePass2" BeforeTargets="MainResourcesGeneration;CoreCompile">
        <ItemGroup>
          <TimestampGeneratedBamlForXamlItem Include="$(IntermediateOutputPath)\**\*.baml"/>
        </ItemGroup>
    
        <PropertyGroup>
          <OriginalFileName>@(TimestampGeneratedBamlForXamlItem->'%(RelativeDir)%(Filename)%(Extension)')</OriginalFileName>
          <BackupFileName>@(TimestampGeneratedBamlForXamlItem->'%(RelativeDir)%(Filename)%(Extension).timestamp')</BackupFileName>
        </PropertyGroup>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(OriginalFileName)"
            OutputFilename="$(BackupFileName)"
            Condition="'$(OriginalFileName)' != ''"/>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(BackupFileName)"
            OutputFilename="$(OriginalFileName)"
            IfFileTextSame="true"
            Condition="'$(OriginalFileName)' != ''"/>
      </Target>
    
      <!-- Restore Timestamp: *_*_wpftmp.AssemblyInfo.g.cs-->
      <Target Name="GeneratedAssemblyInfoFileFix" BeforeTargets="CoreGenerateAssemblyInfo">
        <CreateProperty Value="$(IntermediateOutputPath)$(AssemblyName)_wpftmp.AssemblyInfo.cs"
                        Condition="$(MSBuildProjectName.EndsWith('_wpftmp'))">
          <Output TaskParameter="Value" PropertyName="GeneratedAssemblyInfoFile"/>
        </CreateProperty>
      </Target>
    
      <Target Name="TimestampGeneratedAssemblyInfo" AfterTargets="CoreGenerateAssemblyInfo">
        <ItemGroup>
          <TimestampGeneratedAssemblyInfoItem Include="$(GeneratedAssemblyInfoFile)"/>
        </ItemGroup>
    
        <PropertyGroup>
          <OriginalFileName>@(TimestampGeneratedAssemblyInfoItem->'%(RelativeDir)%(Filename)%(Extension)')</OriginalFileName>
          <BackupFileName>@(TimestampGeneratedAssemblyInfoItem->'%(RelativeDir)%(Filename)%(Extension).timestamp')</BackupFileName>
        </PropertyGroup>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(OriginalFileName)"
            OutputFilename="$(BackupFileName)"
            Condition="'$(OriginalFileName)' != ''"/>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(BackupFileName)"
            OutputFilename="$(OriginalFileName)"
            IfFileTextSame="true"
            Condition="'$(OriginalFileName)' != ''"/>
      </Target>
    
      <!-- Restore Timestamp: *_*_wpftmp.GlobalUsings.g.cs-->
      <Target Name="GeneratedGlobalUsingsFileFix" BeforeTargets="GenerateGlobalUsings">
        <CreateProperty Value="$(IntermediateOutputPath)$(AssemblyName)_wpftmp.GlobalUsings.cs"
                        Condition="$(MSBuildProjectName.EndsWith('_wpftmp'))">
          <Output TaskParameter="Value" PropertyName="GeneratedGlobalUsingsFile"/>
        </CreateProperty>
      </Target>
    
      <Target Name="TimestampGeneratedGlobalUsings" AfterTargets="GenerateGlobalUsings">
        <ItemGroup>
          <TimestampGeneratedGlobalUsingsItem Include="$(GeneratedGlobalUsingsFile)"/>
        </ItemGroup>
    
        <PropertyGroup>
          <OriginalFileName>@(TimestampGeneratedGlobalUsingsItem->'%(RelativeDir)%(Filename)%(Extension)')</OriginalFileName>
          <BackupFileName>@(TimestampGeneratedGlobalUsingsItem->'%(RelativeDir)%(Filename)%(Extension).timestamp')</BackupFileName>
        </PropertyGroup>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(OriginalFileName)"
            OutputFilename="$(BackupFileName)"
            Condition="'$(OriginalFileName)' != ''"/>
    
        <ReplaceIfFileTextChanged
            InputFilename="$(BackupFileName)"
            OutputFilename="$(OriginalFileName)"
            IfFileTextSame="true"
            Condition="'$(OriginalFileName)' != ''"/>
      </Target>
    
      <!-- Workaround for Race Condition on file GeneratedInternalTypeHelper.g.cs --> 
      <!-- See: https://github.com/dotnet/wpf/issues/2281 -->
      <Target Name="Workaround2281Pass1"
              AfterTargets="MarkupCompilePass1"
              BeforeTargets="CoreCompile"
              Condition="($(UseWPF) != '' OR $(UseWPF)) AND $(EnableWorkaround2281) AND Exists('$(IntermediateOutputPath)GeneratedInternalTypeHelper.g.cs')">
        <ItemGroup>
          <!-- Important: Must be the exact same path otherwise it will not get removed. -->
          <Compile Remove="$(MSBuildProjectDirectory)\$(IntermediateOutputPath)GeneratedInternalTypeHelper.g.cs" />
        </ItemGroup>
      </Target>
    
      <Target Name="Workaround2281Pass2"
              AfterTargets="MarkupCompilePass2"
              BeforeTargets="CoreCompile"
              Condition="($(UseWPF) != '' OR $(UseWPF)) AND $(EnableWorkaround2281) AND Exists('$(IntermediateOutputPath)GeneratedInternalTypeHelper.g.cs')">
        <ItemGroup>
          <!-- Important: Must be the exact same path otherwise it will not get removed. -->
          <Compile Remove="$(MSBuildProjectDirectory)\$(IntermediateOutputPath)GeneratedInternalTypeHelper.g.cs" />
        </ItemGroup>
      </Target>
      
      <!-- Check if workaround got applied to MarkupCompilePass1, so it is using refout assemblies -->
      <!-- See: https://github.com/dotnet/wpf/issues/5458#issuecomment-937165247 -->
      <Target Name="Workaround5458Check"
              AfterTargets="MarkupCompilePass1"
              BeforeTargets="CoreCompile"
              Condition="$(EnableWorkaround5458Check) AND ($(UseWPF) != '' OR $(UseWPF)) AND $(EnableWorkaround2281) AND Exists('$(IntermediateOutputPath)GeneratedInternalTypeHelper.g.cs')">
        <PropertyGroup>
          <WinFXFilePath>$(MicrosoftNETBuildTasksDirectoryRoot)\..\..\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.WinFX.targets</WinFXFilePath>
          <WinFXFileContents>$([System.IO.File]::ReadAllText('$(WinFXFilePath)'))</WinFXFileContents>
          <WinFXMarkupCompilePass1TargetOpenRegex>&lt;Target Name="MarkupCompilePass1".*?&gt;</WinFXMarkupCompilePass1TargetOpenRegex>
          <WinFXMarkupCompilePass1TargetOpen>$([System.Text.RegularExpressions.Regex]::Match($(WinFXFileContents), $(WinFXMarkupCompilePass1TargetOpenRegex), System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.Singleline)))</WinFXMarkupCompilePass1TargetOpen>
          <WinFXMarkupCompilePass1TargetDependsOnTargetsHelpRegex>DependsOnTargets=".*;FindReferenceAssembliesForReferences"</WinFXMarkupCompilePass1TargetDependsOnTargetsHelpRegex>
          <WinFXMarkupCompilePass1TargetDependsOnTargetsHelp>$([System.Text.RegularExpressions.Regex]::Match($(WinFXMarkupCompilePass1TargetOpen), $(WinFXMarkupCompilePass1TargetDependsOnTargetsHelpRegex)).Success)</WinFXMarkupCompilePass1TargetDependsOnTargetsHelp>
          <WinFXMarkupCompilePass1TargetCompleteRegex>&lt;Target Name="MarkupCompilePass1".*?&gt;.*?&lt;/Target&gt;</WinFXMarkupCompilePass1TargetCompleteRegex>
          <WinFXMarkupCompilePass1TargetComplete>$([System.Text.RegularExpressions.Regex]::Match($(WinFXFileContents), $(WinFXMarkupCompilePass1TargetCompleteRegex), System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.Singleline).Value)</WinFXMarkupCompilePass1TargetComplete>
          <WinFXMarkupCompilePass1TargetReferencesHelpRegex>References="$([MSBuild]::Escape('@'))\(ReferencePathWithRefAssemblies\)"</WinFXMarkupCompilePass1TargetReferencesHelpRegex>
          <WinFXMarkupCompilePass1TargetReferencesHelp>$([System.Text.RegularExpressions.Regex]::Match($(WinFXMarkupCompilePass1TargetComplete), $(WinFXMarkupCompilePass1TargetReferencesHelpRegex), System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.Singleline).Success)</WinFXMarkupCompilePass1TargetReferencesHelp>
        </PropertyGroup>
    
        <Warning Condition="!$(WinFXMarkupCompilePass1TargetDependsOnTargetsHelp)"
                 Text="The target 'MarkupCompilePass1' of the targets file '$(WinFXFilePath)' has no dependency on the 'FindReferenceAssembliesForReferences' target. Please install a sdk version which supports incremental build for wpf projects. Until this is supported you can apply following patch: https://github.com/dotnet/wpf/issues/5458#issuecomment-937165247"/>
        <Warning Condition="!$(WinFXMarkupCompilePass1TargetReferencesHelp)"
                 Text="The target 'MarkupCompilePass1' of the targets file '$(WinFXFilePath)' is not using the items 'ReferencePathWithRefAssemblies' for the reference property. Please install a sdk version which supports incremental build for wpf projects. Until this is supported you can apply following patch: https://github.com/dotnet/wpf/issues/5458#issuecomment-937165247"/>
        
      </Target>
    </Project>
  6. czdietrich commented on Sep 7, 2022

    @czdietrich

    What is the current state of this issue?
    A small check for our solution (250+ projects, ~70 wpf) showed that incremental builds start working with the given patch from @rainersigwald.

    Anything that prevents that this can be merged into the SDK?

  7. pchaurasia14 commented on Sep 9, 2022

    @pchaurasia14
    Contributor

    @czdietrich - Unfortunately, we weren't able to attend this item for the past releases. We'll certainly target this for upcoming releases.

  8. added
    Investigate
    and removed on Aug 30, 2023
  9. AndreyPolovodov commented on Nov 28, 2025

    @AndreyPolovodov

    Development experience with a large WPF codebase is absolutely disgusting. Many thanks to @rainersigwald for providing us with the SDK patch. I'm wondering why the WPF support team still hasn’t fixed this, and I’d like to upvote the issue.

  10. franchyd commented on Nov 28, 2025

    @franchyd

    Development experience with a large WPF codebase is absolutely disgusting. Many thanks to @rainersigwald for providing us with the SDK patch. I'm wondering why the WPF support team still hasn’t fixed this, and I’d like to upvote the issue.

    There likely is no WPF support team at this moment. See #11188

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Investigate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions