简体   繁体   中英

How to programmatically cancel an embedded MsBuild build

I'm embedding MSBuild directly into a more complex build tool. The relevant code looks roughly like this:

// assume 'using Microsoft.Build.BuildEngine;'
Engine e = Engine();
BuildPropertyGroup props = new BuildPropertyGroup();
props.SetProperty( "Configuration", Config.BuildConfig );
e.BuildProjectFile( projectFile, new string[] { "Build" }, props )

My question is how to cancel this build once it's started, without doing something drastic like terminating the thread. Also, if the project being built is a C++ project, the build will involve at least one sub-process, so canceling the thread isn't even going to really cancel the build.

I don't see any cancel method on the Engine class - does someone know of a way?

This question has come up a few times on the MSDN boards, and unfortunately I haven't seen any other way, apart from terminating the thread. Sadly, in this case, terminating the thread isn't really drastic with it being the only real option.

On a random side note, I am not sure to what extent you are using MSBuild with what you are doing currently. Just wanted to recommend taking a look at the MSBuild Extension Pack on Codeplex if you work with MSBuild on a regular basis.

I had done something similar by running msbuild from command. This starts a process which you could terminate.

From my experience, it is far easier and flexible to manipulate the project files using xml tools and then execute msbuild than it is to programmatically configure your projects the way you have described. It is also more manageable.

It appears is that there's no official way to do this.

For C# builds it's not a huge deal, since they are typically really fast. The best workaround I've come up with for C++ builds is to locate the child processes that are created by the VC build process and terminate them, which stops the MSBuild build. This can be done using a Toolhelp32 snapshot, something like this (omitting P/Invoke garbage):

CreateToolhelp32Snapshot( ToolHelp.SnapshotFlags.Process, 0 );

From here you can determine the parent/child relationship between processes and find the processes spawned by the app that's invoking MSBuild.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM