Skip to content

Build issue with WPF #4299

Open
Open

Description

@jasonmalinowski

Originally posted by @borisf-rnd in dotnet/roslyn#23266 (comment)

Hi,
I am experiencing the exact same issue.
Sometimes second build helps, sometimes not. Sometimes it requires me to rebuild and then build few more times.
Sometimes the build fails with:

Error CS2001: Source file '...\obj\Debug\Views....ToolBar.g.cs' could not be found.

Then, after rebuild:
Unable to delete file "obj\Debug....dll". The process cannot access the file ...\obj\Debug....dll' because it is being used by another process.

Or:

CSC(0,0): Error CS2012: Cannot open '...\obj\Debug...Module.dll' for writing -- 'The process cannot access the file '...\obj\Debug...Module.dll' because it is being used by another process.'

Additional info about the project:

  • I am targeting net48 and net5.0-windows (sdk style project, multi target).
  • Using prism with wpf
  • One of the projects have a postbuild xcopy action (this project makes the most problems).
  • This is a new solution, wasn't upgraded or something.

Must say that this makes it impossible to work, any change in code that requires a build, ends up with 10 min build/rebuild/build rebuild sequence.

Also, there is no issue in the code, it compiles and runs properly (after few attempts of build/rebuild).

Thanks for your help.

Activity

  1. changed the title [-]Hi,[/-] [+]Build issue with WPF[/+] on Mar 18, 2021
  2. predavid commented on Mar 18, 2021

    @predavid
    Contributor

    @jasonmalinowski - thanks for bringing this to our attention.

    Per the suggestion from @borisf-rnd on Build fails on missing generated files dotnet/roslyn#23266: Have you tried to change the target to a single framework (for both net48 and net5.0-windows separately) and try building?

    We'd like help with determining if there is any problem with multitargeting wpf.

  3. self-assigned this
    on Mar 29, 2021
  4. added
    Investigate
    on Mar 29, 2021
  5. added this to the 6.0.0 milestone on Mar 29, 2021
  6. neurolag commented on Jun 24, 2021

    @neurolag

    @predavid how can I find out whether I'm targeting multiple frameworks?
    My solution's .csproj-file looks like this:

    <!-- [...] -->
      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net5.0-windows</TargetFramework>
        <UseWPF>true</UseWPF>
        <CodeAnalysisRuleSet>StyleCop.ruleset</CodeAnalysisRuleSet>
        <GenerateDocumentationFile>true</GenerateDocumentationFile>
      </PropertyGroup>
    <!-- [...] -->

    I don't think I'm targeting any framework other than net5.0-windows
    I'm experiencing the same issue - I find myself unable to build my project using dotnet build because .g.cs-files are allegedly missing.

  7. tormnator commented on Jun 24, 2021

    @tormnator

    @manuth When targeting multiple frameworks you would have something like this:

    <TargetFrameworks>net40;net5.0</TargetFrameworks>

    Notice "TargetFrameworks" in plural.

  8. Joren-Thijs commented on Jul 16, 2021

    @Joren-Thijs

    I have the same problem after moving my WPF project to .NET 5 and then splitting of some of my pages to a user control library.
    Everytime i build the user control library project it fails on some generated file and I have to retry 4 to 5 times. In my case it only happens in Debug mode though.

    Are there any fixes for this? this is a real drag on productivity :(

  9. Joren-Thijs commented on Jul 22, 2021

    @Joren-Thijs

    Same issue in .NET6-preview6

    I get 40 errors saying something doesn't exist in some temporary project file.
    D:\repos\CTESO\CTESO.Visualization.Core\src\CTESO.Visualization.Core.UI.WPF\Components\Login\Login.xaml.cs(17,13): error CS0103: The name 'InitializeComponent' does not exist in the current context [D:\repos\CTESO\CTESO.Visualization.Core\src\CTESO.Visualization.Core.UI.WPF\CTESO.Visualization.Core.UI.WPF_smtynikb_wpftmp.csproj]

    It only works after 4 to 5 rebuilds. Again only in debug mode.

    I would also like to add that i am not targeting multiple frameworks.

  10. ryalanms commented on Jul 27, 2021

    @ryalanms
    Member

    @Joren-Thijs: Is this while multi-targeting? Could you post your csproj? Thanks.

  11. Joren-Thijs commented on Jul 28, 2021

    @Joren-Thijs

    @ryalanms no i am not multitargeting.

    Unfortunatly I'm on vacation now so I will share my csproj next Monday. But it's a very simple csproj, the only custom stuff is the including of some content files like images and disabling the platform compatibility warnings.

    If you want to investigate my specific repo let me know. It's a private one but i can give you access👍

  12. batzen commented on Jul 28, 2021

    @batzen
    Contributor

    I also get sporadically failing builds with missing '.g.cs' files. Projects are: ControlzEx, Fluent.Ribbon and Snoop.
    As it's sporadically I can't provide repro steps. As far as I remember this has started with multi targeting and gets worse when changing the order of target frameworks.

  13. Joren-Thijs commented on Aug 3, 2021

    @Joren-Thijs

    @ryalanms here is my csproj.

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net5.0-windows</TargetFramework>
        <PlatformTarget>AnyCPU</PlatformTarget>
        <UseWindowsForms>true</UseWindowsForms>
        <UseWPF>true</UseWPF>
        <NoWarn>CA1416</NoWarn>
      </PropertyGroup>
    
      <ItemGroup>
        <ProjectReference Include="..\CTESO.Visualization.Core\CTESO.Visualization.Core.csproj" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="Prism.Core" />
        <PackageReference Include="Prism.Wpf" />
        <PackageReference Include="Prism.Unity" />
        <PackageReference Include="Serilog" />
        <PackageReference Include="MaterialDesignThemes" />
        <PackageReference Include="Microsoft.Web.WebView2" />
        <PackageReference Include="AsyncAwaitBestPractices.MVVM" />
        <PackageReference Include="WinCopies.WindowsAPICodePack.Shell" />
      </ItemGroup>
    
      <ItemGroup>
        <!-- Copy assets to output directory -->
        <Content Include="Assets\**\*.*" TargetPath="Assets\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" Pack="true" PackagePath="content\Assets\%(Filename)%(Extension);contentFiles\any\net5.0-windows7.0\Assets\%(Filename)%(Extension)" PackageCopyToOutput="true" />
    
        <!-- Copy localization files to output directory -->
        <Content Include="Localization\**\*.xaml" TargetPath="Localization\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" Pack="true" PackagePath="content\Localization\%(Filename)%(Extension);contentFiles\any\net5.0-windows7.0\Localization\%(Filename)%(Extension)" PackageCopyToOutput="true" />
    
        <!-- Copy webview scripts to output directory -->
        <Content Include="**\*.js" Exclude="bin\**" TargetPath="Resources\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" Pack="true" PackagePath="content\Resources\%(Filename)%(Extension);contentFiles\any\net5.0-windows7.0\Resources\%(Filename)%(Extension)" PackageCopyToOutput="true" />
    
        <!-- Include icon for Nuget package -->
        <None Include="Assets\icon.png" Pack="True" PackagePath="" />
      </ItemGroup>
    
      <!-- Nuget package properties -->
      <PropertyGroup>
        <Authors>CTESO</Authors>
        <Description>Core UI WPF Components for CTESO machine visualization</Description>
        <PackageIcon>icon.png</PackageIcon>
        <PackageIconUrl />
        <RepositoryUrl>https://github.com/Cteso/CTESO.Visualization.Core</RepositoryUrl>
        <RepositoryType>git</RepositoryType>
        <PackageReleaseNotes>CTESO, Visualization, Core, UI, WPF</PackageReleaseNotes>
        <PackageProjectUrl>https://www.cteso.com</PackageProjectUrl>
      </PropertyGroup>
    </Project>
    
  14. mattjuk commented on Aug 11, 2021

    @mattjuk

    Also seeing similar issues with .Net Core 5.0 on WPF. I can frequently have to try and build a project 5- 10 times (with no code changes) until it builds. It seems that there may be a dependency race in the "dotnet build" process.

  15. mattjuk commented on Aug 14, 2021

    @mattjuk

    @ryalanms I have made a useful discovery relating to this, for a single-target Net5.0-Windows build.

    I have been using VSCode to write my WPF code (as I find VS too bulky and slow). I found that if I explicitly turn off file watching for **/obj/** in files.watcherExclude, builds become significantly more reliable -- as in, they haven't broken yet!

    So I suspect what may be happening is that an IDE is detecting a file change after _CompileTemporaryAssembly runs, attempting to open it in exclusive mode, racing against the 2nd stage CoreCompile, which fails if the file has been opened exclusive elsewhere.

  16. 6 remaining items

  17. Joren-Thijs commented on Sep 13, 2021

    @Joren-Thijs

    Can confirm adding **/obj/** to files.watcherExclude in my settings.json in VS Code solves my issue👍

    {
      "files.watcherExclude": {
        "**/obj/**": true,
      }
    }
    

    Thx! @mattjuk

  18. Khaos66 commented on Jun 21, 2022

    @Khaos66

    We're having this issue, too.

    What I found out

    Our project file is quite big, so I'll skip posting it here. But we do use multitargeting <TargetFrameworks>net48;net6.0-windows10.0.19041.0</TargetFrameworks>.

    I used the /bl flag on msbuild to save the build log and this great tool to view it.
    msbuild .\MyProject.csproj /bl /t:Clean,Build

    Process = "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\amd64\MSBuild.exe"
    MSBuild-Version = "17.2.1+52cd2da31"

    It seems like the .g.cs files are generated in the MarkupCompilePass1 target.

    So I added a custom target to the project file, to see if the .g.cs files are actually existing after the markup pass:

      <Target Name="Test" AfterTargets="MarkupCompilePass1">
        <Message Condition="Exists(%(_GeneratedCodeFiles.Identity))" Text="File exists: %(_GeneratedCodeFiles.Identity)" />
        <Error Condition="!Exists(%(_GeneratedCodeFiles.Identity))" Text="File missing: %(_GeneratedCodeFiles.Identity)" />
      </Target>

    Not sure if related, but on the next build I had a lot of these errors:

    C:\Program Files\dotnet\sdk\6.0.301\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.WinFX.targets(734,5):
     error BG1002: Die Datei "E:\[...]\obj\Debug\net6.0-windows10.0.19041.0\UIImage.baml" wurde
     nicht gefunden. 
    

    Which translates from German to English: error BG1002: File [...].baml not found.


    Anyways, on the next build I was back to the .g.cs files not found error.
    The custom target was run and all files from the _GeneratedCodeFiles ItemGroup passed the Exists condition.

    So I changed the custom target to run right before the CoreCompile target:

      <Target Name="Test" BeforeTargets="CoreCompile">
        <Message Condition="Exists(%(Compile.Identity))" Text="File exists: %(Compile.Identity)" />
        <Error Condition="!Exists(%(Compile.Identity))" Text="File missing: %(Compile.Identity)" />
      </Target>

    And on the next build I got these errors:

    "E:\...\Project.csproj" (Clean;Build Ziel) (1) ->
    "E:\...\Project.csproj" (Build Ziel) (1:4) ->
    (Test Ziel) ->
      E:\...\Project.csproj(485,5): error : File missing: E:\...\obj\Debug\net48\UIImage.g.cs
    
    "E:\...\Project.csproj" (Clean;Build Ziel) (1) ->
    "E:\...\Project.csproj" (Build Ziel) (1:4) ->
    (Test Ziel) ->
      E:\...\Project.csproj(485,5): error : File missing: E:\...\obj\Debug\net6.0-windows10.
    0.19041.0\UIImage.g.cs
    

    So the custom target is doing it's job and detects that the generated files are missing.
    But when I use the file explorer to inspect the folder, the files are there.

    The next build was successfull (for a change =D)

    But the next build passed the custom test target successfully and failed in CSC, again =/
    Whats strage this time, is that the net48 build was successfull and only the net6.0 build had the issue.
    Although the custom test target was passed for both target frameworks successfully.

    I then changed the custom target to call a powershell script with a simplte Test-Path statement (which took forever to run per file within our project, that has A LOT of files). But the delay fixed the issue, so the next test was to just wait a bit before continuing with CoreComplie.

    I used different ways to cause a sleep, but ended up with this as the best aproach:

      <UsingTask TaskName="Sleep" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
          <!-- Delay in milliseconds -->
          <Delay ParameterType="System.Int32" Required="true" />
        </ParameterGroup>
        <Task>
          <Code Type="Fragment" Language="cs">
            <![CDATA[
    System.Threading.Thread.Sleep(this.Delay);
    ]]>
          </Code>
        </Task>
      </UsingTask>
    
      <Target Name="WaitForFiles" BeforeTargets="CoreCompile">
        <PropertyGroup>
          <WaitTime>5000</WaitTime>
        </PropertyGroup>
        <Message Text="Waiting for $(WaitTime)ms" Importance="high" />
        <Sleep Delay="$(WaitTime)"/>
      </Target>

    I started with only 1000ms of wait time and found that 5000ms gives the most stable result.

  19. Khaos66 commented on Jun 21, 2022

    @Khaos66

    Now also tried to open each file before CoreCompile is run.

    But still having the same issue. The open is successfull, CSC throws an error about some *.g.cs files missing.
    Whats strange is, that our project has A LOT of xaml files and only a few of them are not found by CSC. And it looks like it's allways the same few files missing.

    Here's my target for waiting for file access:

      <UsingTask TaskName="WaitForFiles" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
        <ParameterGroup>
          <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
        </ParameterGroup>
        <Task>
            <Using Namespace="System.IO" />
            <Using Namespace="System.Linq" />
            <Code Type="Fragment" Language="cs">
            <![CDATA[
            Log.LogMessage(MessageImportance.High, string.Format("Waiting for {0} files to be accessable...", Files.Length));
            Files.AsParallel().ForAll(async file => {
              while(true)
              {
                FileStream stream = null;
                bool wait = false;
                try
                {
                  stream = File.Open(file.ItemSpec.ToString(), FileMode.Open, FileAccess.ReadWrite);
                  Log.LogMessage(MessageImportance.High, string.Format("File {0} is accessable", file.ItemSpec));
                  return;
                }
                catch(Exception)
                {
                  Log.LogWarning(string.Format("File {0} is still locked by another process...", file.ItemSpec));
                  wait = true;
                }
                finally
                {
                  if (stream != null)
                    stream.Dispose();
                }
                if (wait)
                  await System.Threading.Tasks.Task.Delay(200);
              }
            });
          ]]>
          </Code>
        </Task>
      </UsingTask>
    
      <Target Name="WaitForFiles" BeforeTargets="CoreCompile">
        <WaitForFiles Files="@(Compile)"/>
      </Target>
  20. KevinCattell commented on Jul 20, 2022

    @KevinCattell

    Hi @Khaos66, any more info on this? We've recently upgraded from 3.1 to .net 6 and are seeing this frequently on our build servers (approx 1 in 4). It occurs on different projects, and on different files within the projects. We're struggling to understand if the cause is a race condition in the build process itself or an interaction with anti-virus/some other file-system watcher.

  21. Khaos66 commented on Jul 29, 2022

    @Khaos66

    @KevinCattell Well, I'm using this build target now. It prevents the issue from happening in 90% of my builds. But it also kills dev productivity as each build now takes longer...

      <UsingTask TaskName="Sleep" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
        <ParameterGroup>
          <!-- Delay in milliseconds -->
          <Delay ParameterType="System.Int32" Required="true" />
        </ParameterGroup>
        <Task>
          <Code Type="Fragment" Language="cs"><![CDATA[
    System.Threading.Thread.Sleep(this.Delay);
    ]]></Code>
        </Task>
      </UsingTask>
      <Target Name="WaitForFiles" BeforeTargets="CoreCompile">
        <PropertyGroup>
          <WaitTime>5000</WaitTime>
        </PropertyGroup>
        <Message Text="Waiting for $(WaitTime)ms" Importance="high" />
        <Sleep Delay="$(WaitTime)" />
      </Target>
  22. MichaeIDietrich commented on Jul 29, 2022

    @MichaeIDietrich
    Contributor

    Just out of curiosity. You could try to use MSBuild's <Copy /> task on those blocked files and copy them to some random temp directory. <Copy /> has a built-in check when a file is blocked trying to detect the process that blocks the file.
    At least this could help to find the cause of this issue.

  23. dro123 commented on Jul 29, 2022

    @dro123

    I have a similar problem but with "old style" .csproj and .NET Framework 4.7.2.

    The problem is that the files exist and are not blocked before the CoreCompile target (and I even checked afterwards). That's why the WaitForFiles target from @Khaos66 does not help.
    I do have to add, that I only have the issue when I build with VisualStudio (devenv.exe or devenv.com). If I build directly with msbuild.exe the issue is gone.
    The solution file I'm using has a few build dependencies that are not project references (ProjectSection(ProjectDependencies) = postProject) and msbuild.exe does some wierd stuff with that. That's why I use devenv.com on our CI server to build the solution.
    Maybe my issue is a different one, but the result is the same.

    This is what I tried and nothing showed that there's a problem with the "missing files" other than the CoreCompile task that says the files are "missing":

      <UsingTask TaskName="WaitForFiles" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
        <ParameterGroup>
          <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
        </ParameterGroup>
        <Task>
          <Using Namespace="System.IO" />
          <Using Namespace="System.Linq" />
          <Code Type="Fragment" Language="cs">
            <![CDATA[
                Files.AsParallel().ForAll(
                    file =>
                    {
                        var fileName = file.ItemSpec.ToString();
                        var startTime = DateTime.UtcNow;
                        while (true)
                        {
                            try
                            {
                                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                                {
                                    if (fs.Length > 0)
                                    {
                                        Log.LogMessage(MessageImportance.High, $"File {fileName} is available!");
                                        return;
                                    }
                                }
                            }
                            catch
                            {
                                // ignore
                            }
    
                            if ((DateTime.UtcNow - startTime).TotalSeconds > 10)
                            {
                                Log.LogWarning($"File {fileName} is still locked by another process... Stop waiting and give up.");
                                return;
                            }
    
                            Log.LogWarning($"File {fileName} is still locked by another process...");
                            System.Threading.Thread.Sleep(1000);
                        }
                    });
          ]]>
          </Code>
        </Task>
      </UsingTask>
    
      <Target Name="WaitForGeneratedCodeFiles" AfterTargets="MarkupCompilePass1">
        <Message Importance="High" Text="$(MSBuildProjectName): WaitForGeneratedCodeFiles" />
        <WaitForFiles Files="@(_GeneratedCodeFiles)"/>
        <Message Importance="High" Text="$(MSBuildProjectName): /WaitForGeneratedCodeFiles" />
      </Target>
    
      <Target Name="WaitForAllFilesBeforeCompile" BeforeTargets="CoreCompile">
        <Message Importance="High" Text="$(MSBuildProjectName): WaitForAllFilesBeforeCompile" />
        <WaitForFiles Files="@(Compile)"/>
        <Message Importance="High" Text="$(MSBuildProjectName): /WaitForAllFilesBeforeCompile" />
      </Target>
    
      <Target Name="CheckAllFilesAfterCompile" AfterTargets="CoreCompile">
        <Message Importance="High" Text="$(MSBuildProjectName): CheckAllFilesAfterCompile" />
        <WaitForFiles Files="@(Compile)"/>
        <Message Importance="High" Text="$(MSBuildProjectName): /CheckAllFilesAfterCompile" />
      </Target>
  24. Khaos66 commented on Jul 29, 2022

    @Khaos66

    @dro123 See my latest comment with the 5000ms wait target. maybe it helps

  25. xhuan8 commented on Apr 4, 2023

    @xhuan8

    Any progress on this issue? it still exists on .NET 6.
    Some thread lock the dll file after debuging, sometimes will release after a few seconds, sometimes have to restart VS or kill the process.

  26. victorvlasak-benteler commented on Mar 8, 2024

    @victorvlasak-benteler

    We had a multitarget project but had set

    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
    

    Which also produced these spontaneous issues.

    Setting it to true for the multitarget project resolves this issue, check if you dont have it in project file that is setting this property to false or a Directory.Build.props, as was our case.

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

Metadata

Metadata

Assignees

Labels

Investigateurgent

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions