0

I have a web service with three methods: StartReport(...), IsReportFinished(...) and GetReport(...), each with various parameters. I also have a client application (Silverlight) which will first call StartReport to trigger the generation of the report, then it will poll the server with IsReportFinished to see if it's done and once done, it calls GetReport to get the report. Very simple...
StartReport is simple. It first generates an unique ID, then it will use System.Threading.Tasks.Task.Factory.StartNew() to create a new task that will generate the report and finally return the unique ID while the task continues to run in the background. IsReportFinished will just check the system for the unique ID to see if the report is done. Once done, the unique ID can be used to retrieve the report.

But I need a way to cancel the task, which is implemented by adding a new parameter to IsReportFinished. When called with cancel==true it will again check if the report is done. If the report is finished, there's nothing to cancel. Otherwise, it needs to cancel the task.
How do I cancel this task?

Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149
  • Normally to terminate a thread, I would use a shared and synchronised variable and have the working thread check the variable at given intervals throughout it's workload to see if it should not continue. Would such a pattern work for you? Or are you looking to identify the thread that the factory used in order to abort it directly? – Smudge202 Jul 08 '11 at 09:21
  • I wished it was possible to use such a shared and synchronised variable but unfortunately, the service is stateless so I cannot keep a reference to such a variable. The whole thing will be run on Azure and due to load balancing, I don't even know if the polling method will be executed on the same system as where the thread is running! – Wim ten Brink Jul 14 '11 at 08:47

1 Answers1

1

You could use a cancellation token to cancel TPL tasks. And here's another example.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But once the service call is done and the task is running, I have no way to reference that cancellation token again! – Wim ten Brink Jul 14 '11 at 14:04
  • 1
    @Wim ten Brink, you could store this cancellation token into the ApplicationState under the associated ID of the task and when later you wanted to cancel the task you would pass this id to the web method which will fetch the cancellation token back from the application state and cancel the task. – Darin Dimitrov Jul 14 '11 at 14:41
  • Consider inlining the comment and possibly add guidance on not actually going that approach in favor of more reliable ways to perform long-running operations in ASP.Net (found due to https://stackoverflow.com/questions/74292514/what-is-the-best-way-to-cancel-a-task-on-a-web-form/74292899). – Alexei Levenkov Nov 02 '22 at 17:04