I am currently in the process of retrofitting our long-running methods to be cancelable. I am planning on using System.Threading.Tasks.CancellationToken to implement that.
Our methods generally perform a few long-running steps (sending commands to and then waiting for hardware mostly), e.g.
void Run()
{
Step1();
Step2();
Step3();
}
My first (maybe stupid) thought on cancellation would transform this into
bool Run(CancellationToken cancellationToken)
{
Step1(cancellationToken);
if (cancellationToken.IsCancellationRequested)
return false;
Step2(cancellationToken);
if (cancellationToken.IsCancellationRequested)
return false;
Step3(cancellationToken);
if (cancellationToken.IsCancellationRequested)
return false;
return true;
}
which frankly looks horrible. This "pattern" would continue inside the single steps, too (and they are necessarily rather longish already). This would make Thread.Abort() look rather sexy, although I know its not recommended.
Is there a cleaner pattern to achieve this that does not hide away the application logic beneath lots of boilerplate code?
Edit
As an example for the nature of the steps, the Run
method could read
void Run()
{
GiantRobotor.MoveToBase();
Oven.ThrowBaguetteTowardsBase();
GiantRobotor.CatchBaguette();
// ...
}
We are controlling different hardware units that need to be synchronized to work together.
Step(int number)
? Such that you can loop through from 1 to 3 and check if the cancellation token is requested only once?Thread.Abort()
call and critical sections? Then, you'd only have to mutex critical code (saving state perhaps), and let Thread.Abort() kill the rest.Maybe
Monad. Seems a good conceptual fit.