How to stop multiple threads (Tasks) from an external REST API call?

509 Views Asked by At

So what I am dealing with here is a pretty complex server application that performs quite a long, complex and lengthy operation involving a number of threads and a number of tasks (yes, some are created as Tasks and some are "manually" created threads.

The complex and lengthy process we are talking here is triggered using a REST API call (assume a web page generates the request object based on user input), and provides the user with an ID to poll for the progress of the operation.

I am looking for an efficient way to allow the user to click an "Abort/Stop" button that will stop this whole orchestra of threads/tasks.

(keep in mind this server can process a number of requests as described above).

I have looked into a number of options, all of which seem to require the threads/tasks themselves to monitor for an "abort flag" during their operation loop and break out of the loop should it be required.

Obviously using Thread.Abort is a big no no.

I have thought about having some kind of an abstract class (say: AbortableThread) all which all my "worker" threads will have to implement, where the only abstract function would be Abort(), so that each thread can end in a clean manner, closing and finishing whatever it needs to.

This way, I would perhaps be able to keep tabs on the threads that have been spawned by a specific user request and just call Abort() in a foreach loop.

Despite that, I still try to figure out how would it be able to break into the loops I run, so my 2nd though would be that this "abstract" class could have a property shouldBreak which will again I will be able to set from "outside", but this then brings me back to (almost) square one where I have to add "logic" into my threads to be able to abort.

A 3rd idea I came up with is to have my logical loops call Abort() on every loop, without any validation whether an abort is currently required or not, where I will check my abstract's base class shouldBreak bool and act accordingly should it be required.

There are no code examples and I have decided I would rather figure this out in high level before I dive into implementation.

Thank you for reading this long question!

0

There are 0 best solutions below