问题
I'm using ASP.NET WebForms. In PostBack I create a Task(task is very long running). In the html page I need a button that can cancel this task. 1. I click button GetResults that Run a task on the server 2. After some waiting I click button Cancel and I need the task will be cancelled
How can I do this?
回答1:
Though, you can do it, it is generally not a good idea to create a long running task within ASP.NET, especially if they are background tasks.
Phil Haack has a great article on this - http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/
Here is another good article on that topic - http://blog.stephencleary.com/2012/12/returning-early-from-aspnet-requests.html
You can consider things like message bus for this. You can also consider a simple TaskQueue table in the database to which your web application will insert a record corresponding to your task with status "Pending". Then you can have a background service (like windows service) that reads "Pending" tasks and marks them as "InProgress" during processing and "Complete" when its done. That way while the task is "Pending", you can have the user cancel the task from UI, which will simply delete the "Pending" record from the database.
Another option is to use a solution such as this - http://hangfire.io/
来源:https://stackoverflow.com/questions/26204378/cancelling-long-running-tasks-asp-net