Running Targets in Parallel in MSBuild


UPDATE: 07 March 2012 – a task to run targets in parallel is now provided in the MSBuild Extension Pack. See ‘Executing MSBuild Targets in Parallel

MSBuild doesn’t support running targets in parallel, but rather supports running projects in parallel. I was recently shown a ‘trick’ by Dan Moseley of the MSBuild team in getting MSBuild to execute targets in parallel.

Let’s take the common scenarios where you have a  bunch of files and you have a target which operates on those files. You would like to run that target for each file in parallel during your build.

To accomplish this you could do the following:

<Project DefaultTargets=”ExecuteTargetsOnParallel” ToolsVersion=”4.0″ xmlns=”http://schemas.microsoft.com/developer/msbuild/2003″>
  <!– Create an ItemGroup of files –>
  <ItemGroup>
<files Include=”a;b;c”/>
</ItemGroup>

<Target Name=”TheWork”>
   <!– Do your real work on each file here. –>
    <Message Text=”$(thefile)”/>
</Target>

<Target Name=”ExecuteTargetsOnParallel”>
    <!– Create an itemgroup of temporary projects using the current MSBuild file and passing in the files –>
    <ItemGroup>
<TempProjects Include=”$(MSBuildProjectFile)” >
<Properties>thefile=%(files.identity)</Properties>
</TempProjects>
</ItemGroup>
   <!– Execute the temporary projects in parallel –>
    <MSBuild Projects=”@(TempProjects)” BuildInParallel=”true” Targets=”TheWork” />
</Target>
</Project>

Given this, perhaps we could do with a Task in the MSBuild Extension Pack called something like ExecTargetsInParallel which took a project, target and properties and did it all under the covers for the user…

2 Replies to “Running Targets in Parallel in MSBuild”

Leave a comment