0

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!

MichaelEr
  • 75
  • 2
  • 8
  • 1
    You should read on "C# task cancellation"... Side note: you can't find examples of what you are looking for because long running process as part of ASP.Net server do not work... So no one actually needed such functionality. – Alexei Levenkov Jun 21 '21 at 18:28
  • 1
    You should use a `CancellationToken`, which is designed for this purpose. It has utilities for checking for cancellation as well as a `TaskCanceledException` you can catch. See [Cancellation in Managed Threads](https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads). That being said, running long-running transactions inside a web server process isn't a great idea. – John Wu Jun 21 '21 at 19:18

0 Answers0