private bool TryBeginBuild(bool designTime, bool requiresUIThread = false)
{
IVsBuildManagerAccessor accessor = null;
if (this.Site != null)
{
accessor = this.Site.GetService(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor;
}
bool releaseUIThread = false;
try
{
// If the SVsBuildManagerAccessor service is absent, we're not running within Visual Studio.
if (accessor != null)
{
if (requiresUIThread)
{
int 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)
{
int 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
{
BuildParameters buildParameters = new BuildParameters(this.buildEngine ?? ProjectCollection.GlobalProjectCollection);
BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
}
this.buildInProcess = 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());
}
}
}