private bool TryBeginBuild(bool designTime, bool requiresUIThread = false)
{
IVsBuildManagerAccessor accessor = null;
if (Site != null)
{
accessor = Site.GetService(typeof (SVsBuildManagerAccessor)) as IVsBuildManagerAccessor;
}
var releaseUIThread = false;
try
{
// If the SVsBuildManagerAccessor service is absent, we're not running within Visual Studio.
if (accessor != null)
{
if (requiresUIThread)
{
var result = accessor.ClaimUIThreadForBuild();
if (result < 0)
{
// Not allowed to claim the UI thread right now. Try again later.
return false;
}
releaseUIThread = true;
// assume we need to release this immediately until we get through the whole gauntlet.
}
if (designTime)
{
var result = accessor.BeginDesignTimeBuild();
if (result < 0)
{
// Not allowed to begin a design-time build at this time. Try again later.
return false;
}
}
// We obtained all the resources we need. So don't release the UI thread until after the build is finished.
releaseUIThread = false;
}
else
{
var buildParameters =
new MSBuildExecution.BuildParameters(buildEngine ??
MSBuild.ProjectCollection.GlobalProjectCollection);
MSBuildExecution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
}
BuildInProgress = true;
return true;
}
finally
{
// If we were denied the privilege of starting a design-time build,
// we need to release the UI thread.
if (releaseUIThread)
{
Debug.Assert(accessor != null,
"We think we need to release the UI thread for an accessor we don't have!");
Marshal.ThrowExceptionForHR(accessor.ReleaseUIThreadForBuild());
}
}
}