c# - 加快 MSBuild 构建过程

标签 c# performance compilation msbuild msbuild-4.0

我的构建过程运行良好,但对于一个非常小的项目来说需要近 3 秒。

如何加快构建过程?

日志文件太大,无法发布。请随意询问有关记录器输出的问题,然后我将发布请求的部分。

构建项目的 C# 方法

private void CompileCode()
        {
            using (var buildManager = new BuildManager())
            {
                var result = buildManager.Build(this.CreateBuildParameters(), this.CreateBuildRequest());

                if (result.OverallResult == BuildResultCode.Failure)
                {
                    // Error handling
                    var stringbuilder = new StringBuilder();

                    using (var reader = new StreamReader(NameDebuggerLogFile))
                    {
                        stringbuilder.Append(reader.ReadToEnd());
                    }

                    throw new CompilerException(stringbuilder.ToString());
                }
            }
        }

        private BuildParameters CreateBuildParameters()
        {
            var projectCollection = new ProjectCollection();
            var buildLogger = new FileLogger { Verbosity = LoggerVerbosity.Detailed, Parameters = "logfile=" + NameDebuggerLogFile };
            var buildParameters = new BuildParameters(projectCollection) { Loggers = new List<ILogger>() { buildLogger } };
            return buildParameters;
        }

        private BuildRequestData CreateBuildRequest()
        {
            var globalProperties = new Dictionary<string, string>();
            var buildRequest = new BuildRequestData(FolderPath + NameProjectFile, globalProperties, null, new[] { "Build" }, null, BuildRequestDataFlags.ReplaceExistingProjectInstance);
            return buildRequest;
        }

用于构建过程的项目文件

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <AssemblyName>GeneratedFlexForm</AssemblyName>
    <OutputPath>DLL</OutputPath>
    <OutputType>Library</OutputType>
    <DebugType>none</DebugType>
    <DebugSymbols>false</DebugSymbols>
    <Optimize>false</Optimize>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.Web" />
    <Reference Include="System.Web.Services" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Design" />
    <Reference Include="System.Data" />
    <Reference Include="System.Core" />
    <Reference Include="System.Management" />
    <Reference Include="System.Configuration" />
    <Reference Include="System.Xaml">
      <RequiredTargetFramework>4.0</RequiredTargetFramework>
    </Reference>
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <!--<Reference Include="FlexForms.Core" />-->
    <Reference Include="FlexForms.Core, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>Library\FlexForms.Core.dll</HintPath>
    </Reference>
    <Reference Include="Gizmox.WebGUI.Forms">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>Library\Gizmox.WebGUI.Forms.dll</HintPath>
    </Reference>
    <Reference Include="Gizmox.WebGUI.Common">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>Library\Gizmox.WebGUI.Common.dll</HintPath>
    </Reference>
    <Reference Include="FlexForms.ServiceProviders">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>Library\FlexForms.ServiceProviders.dll</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Page Include="FlexForm.xaml">
      <Generator>MSBuild:Compile</Generator>
      <DependentUpon>RadioButtonValueConverter.cs</DependentUpon>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="FlexForm.xaml.cs">
      <DependentUpon>FlexForm.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="UserCode.cs">
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="RadioButtonValueConverter.cs">
      <SubType>Code</SubType>
    </Compile>
    <Resource Include="datacontext.xml"/>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

构建期间收集的记录器输出(由于文件大小,仅最后几行)

Done building project "projectfile.csproj".

Build succeeded. 0 Warning(s) 0 Error(s)

Time Elapsed 00:00:02.68

编辑:

我希望我可以在这里引用Seva Titov:

Building WPF is really tricky, for example XAML files get re-compiled twice (see MSDN). You cannot easily replicate it with just csc.exe. If you have XAML in your project, you have to use MSBuild. – Seva Titov

这就是为什么我必须坚持使用 MSBuild。

无论如何,我有一些提高性能的想法:

问题 1: 这是我的日志文件中的一个片段,其中表示 MSBuild 将在解析依赖项时处理 .winmd、.dll 和 .exe 文件。

AllowedAssemblyExtensions:
    .winmd
    .dll
    .exe

由于我只有 .dll 文件,所以我想禁用 MSBuild 考虑 .winmd 文件,这几乎是我所有依赖项的情况。 (下面的例子)

Primary reference "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35". Resolved file path is "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\PresentationCore.dll". Reference found at search path location "{TargetFrameworkDirectory}". For SearchPath "{TargetFrameworkDirectory}". Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\PresentationCore.winmd", but it didn't exist.

解决方案:1 我必须修改我的 CreateBuildRequest() 方法:

private BuildRequestData CreateBuildRequest()
{
    var globalProperties = new Dictionary<string, string>();
    // Related to idea 1           
    globalProperties.Add("ExpandSDKAllowedReferenceExtensions", ".dll");
    globalProperties.Add("AllowedReferenceAssemblyFileExtensions", ".dll");
    globalProperties.Add("AllowedReferenceRelatedFileExtensions", string.Empty);
    // Related to idea 2     
    globalProperties.Add("BuildProjectReferences", "false");
    globalProperties.Add("BuildInParallel", "true");
    var buildRequest = new BuildRequestData(FolderPath + NameProjectFile, globalProperties, "4.0", new[] { "Build" }, null, BuildRequestDataFlags.IgnoreExistingProjectState);
    return buildRequest;
}

编辑2: 想法 2: 有谁知道如何包含/maxcpucount 或/m 开关来并行构建我的项目? 对此进行了解释MSDN page但我不知道如何将其应用到上面列出的项目文件

解决方案 2: 请参阅解决方案 1,但它没有太大变化。

编辑3: 经过几个小时的玩耍后,我想我将不得不放弃。我看到的唯一选择是总体上减少依赖性。但我稍后会再讨论这个问题。

有点不相关:

> Task Performance Summary:
>         0 ms  CreateItem                                 1 calls
>         0 ms  AssignCulture                              1 calls
>         0 ms  CallTarget                                 2 calls
>         0 ms  FindAppConfigFile                          1 calls
>         0 ms  Delete                                     4 calls
>         0 ms  GetFrameworkPath                           1 calls
>         0 ms  ConvertToAbsolutePath                      1 calls
>         0 ms  MakeDir                                    1 calls
>         0 ms  Message                                    5 calls
>         0 ms  AssignTargetPath                           6 calls
>         1 ms  FindUnderPath                              5 calls
>         1 ms  FileClassifier                             1 calls
>         1 ms  RemoveDuplicates                           2 calls
>         1 ms  CreateCSharpManifestResourceName           1 calls
>         1 ms  ReadLinesFromFile                          1 calls
>        15 ms  ResolveAssemblyReference                   1 calls
>        21 ms  ResourcesGenerator                         1 calls
>        56 ms  Copy                                       2 calls
>       299 ms  GenerateTemporaryTargetAssembly            1 calls
>       502 ms  Csc                                        2 calls
>       725 ms  MarkupCompilePass1                         1 calls
>       814 ms  MarkupCompilePass2                         1 calls
> 
> Build succeeded.
>     0 Warning(s)
>     0 Error(s)
> 
> Time Elapsed 00:00:02.27

最佳答案

为了回答您的直接问题,您无法采取任何措施来加快 msbuild 的速度。如果您的机器使用 SSD,我希望它运行得更快,但这可能不是您正在寻找的解决方案。

我唯一能想到的就是完全停止使用 msbuild。它所做的只是驱动 C# 编译器。那么为什么要费心使用 msbuild 呢?直接使用C#编译器就可以了。例如通过 CSharpCodeProvider

关于c# - 加快 MSBuild 构建过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15658321/

相关文章:

c - 使用 OpenMP 优化循环后没有性能提升

ios - 由于 titleForHeaderInSection 导致 iOS 性能降低

c++ - 设置了 CPPFLAGS 但仍未找到 header

assembly - OpenCL 在线编译:从 cl::program 或 cl::kernel 获取程序集

c# - 海量 ORM 和继承

c# - SignalR - Multi-Tenancy 依赖注入(inject)

c# - 我可以告诉 bindingRedirect 始终使用最新的可用版本吗?

java - 为什么这段代码很慢?

c++ - LLVM 中编译单元的正确抽象是什么?

c# - ASP.NET 5 Web API 项目模板不允许使用 Entity Framework