Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel build process in VisualStudio for a long running custom build tool?

I have a custom build step. In this step I have a large long running tool to convert a database into a special static compressed format. This tool handles nearly 2GB of data and runs up 30 minutes.

The tools handles Ctrl+C and Ctrl+Break. And can easily stopped when running from the command line.

But inside VisualStudio (I use currently VS2015) I can't stop this tool to run. The compiler and linker stops when I choose Build -> Cancel. But my tool continues to run.

It seams that VS doesn't handle the break signal to the processes it starts.

Is there any trick or setting to abort tools in the build process, without using the task manager?

like image 885
xMRi Avatar asked Oct 29 '22 09:10

xMRi


1 Answers

The compiler and linker "know" to stop when you cancel the build because they run as MSBuild Tool Task, and are sensitive to ToolCanceled event.
While you cannot do the same thing with custom build step, you can wrap your tool with a class that extends ToolTask and kill your tool when ToolCanceled event is triggered.

To do that you will need to register a task in your msbuild project file. This is also possible with inline tasks with <Code Type="class" ...

ToolTask also implements ICancelableTask so you can override Cancel() method in your class and stop your tool when it is called.
Cancel() method will be called by MSBuild when the build is cancelled.

Here is an example of an inline task that implements Cancel():

 <UsingTask TaskName="MyTool" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">

    <ParameterGroup> 
      <!-- Tool parameters -->     
    </ParameterGroup>

    <Task>
      <Code Type="Class" Language="cs">
        <![CDATA[  

      using Microsoft.Build.Utilities;
      using Microsoft.Build.Framework;
      using System;

      public class MyTool : Task, ICancelableTask
      {
         public override bool Execute()
         {
           Log.LogMessage(MessageImportance.High, "MyTool: Build started!");

           // Code to run your tool...
         }

         public void Cancel()
         {         
           Log.LogMessage(MessageImportance.High, "MyTool: Build cancelled!");

           // Code to stop your tool...          
         }
      }

       ]]>
      </Code>
    </Task>
  </UsingTask>
like image 67
Amir Gonnen Avatar answered Jan 02 '23 19:01

Amir Gonnen