How do you write an MSBuild task to support cancellation?

I have a special MSBuild task for xUnit.net. When a task starts, if I press Ctrl + C, it tries to “cancel the task”, but of course it fails (because my task does not support cancellation). No amount of MSDN or Google-fu search queries landed on the solution. Since I cannot find an obvious interface to implement, I assume that perhaps cancellation is supported by some convention.

Has anyone done this before and knows what it takes to cancel a job?

+7
source share
2 answers

Your task should complete ICancelableTask . This is a very simple interface added in 4.0.

Basically you just add the Cancel () method. He should be ready to call in another thread at any time and return immediately. Then your task should return from Execute. Usually you set the boolean flag inside Cancel (). Then inside your task, as a rule, you process each input in turn - for example, copying one file after another - and at each iteration check the flag; if true, break free. It doesn't matter if you return true or false from Execute in this context.

If you exit ToolTask ​​- if your task generates a tool, it is highly recommended that you do this, since it saves a lot of code, processes asynchronous logs and other things - then it already processes Cancel automatically. When “Cancel” occurs, she kills the tool that he spawned, and all his children. The tasks of the C ++ command in some cases override this default behavior, so their compiler / linker takes a few seconds to clear their half-written outputs before returning.

(Trivia: when I first implemented this in MSBuild, I accidentally made VS bluescreen a field occasionally. It was almost sent to VS10 beta, but it was detected just in time. Bluescreen was because the logic for determining the process tree was wrong and will sometimes kill system process unfortunately.

Dan

+14
source

I know that you are well aware of the task hierarchy, but on the sidelines this is what you are looking for and it is just a fact that you are not implementing ToolTask ...

Inside MSBuild 2nd ed it says (p118) from ToolTask.Cancel

This method is called to cancel the task. When this method is called by MSBuild, if the task is not completed, it will be forced to complete.

There are no other cancellation links in it.

0
source

All Articles