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 thoughts on “Running Targets in Parallel in MSBuild

  1. Pingback: Leveraging MSBuild’s BuildInParallel (with caution) « FreeToDev

  2. Pingback: Dew Drop – December 4, 2010 | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s