3

I have an AJAX function on a view that calls an Action on one of my controllers to get a JSON object. The problem is that it takes a while to create the object. If the user reloads the page, then the AJAX call runs again. As far as I can tell the action is still running from the last request, but the response is no longer relevant because the new AJAX call is waiting for the new response.

My question is, how do I keep the action from continuing if the user leaves the view that called it?

Ajax:

$.ajax({
    type: "get",
    url: "/Alert/GetWallboardAlerts",
    cache: false,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (result) { ... }
});

Controller action:

public ActionResult GetWallboardAlerts()
{
    //...do long running stuff
    //...still doing stuff when page reloaded or I navigate elsewhere
    return Json(alertString, JsonRequestBehavior.AllowGet);
}
Peter Szekeli
  • 2,712
  • 3
  • 30
  • 44
aufty
  • 407
  • 2
  • 9
  • 26
  • If a user leaves the view that called it the action will proceed, but the browser won't be waiting for a response so when the action completes it will be disposed. – jasonwarford Feb 18 '16 at 20:18
  • As far as I know, you can't. At least without some fancy thread programming, which I would not recommend. – A. Burak Erbora Feb 18 '16 at 20:19
  • If you want to kill the request you could try this: http://stackoverflow.com/a/446626/433234 – jasonwarford Feb 18 '16 at 20:20
  • @jasonwarford but that would kill the ajax request, not the GetWallboardAlerts() which will keep running. – A. Burak Erbora Feb 18 '16 at 20:21
  • You can put your long action in a new thread, and abort it if new task comes in - something like this: http://stackoverflow.com/questions/4783865/how-do-i-abort-cancel-tpl-tasks – Ziv Weissman Feb 18 '16 at 20:27

1 Answers1

1

I don't think you can. Once you made a request to the server, you could close the browser but the request will still be executed.

This is just an idea:

1) Caller makes an AJAX request and provides a unique value (could be a guid).

2) Handle the page reload event and the close event and send a new AJAX request with the same unique key requesting a cancellation.

3) The long process task that is executed on the server should check for a flag that indicates that the task has been canceled.

You could also use a WebSocket for a task like this so the server could ping the client (like a "still alive" request). If you are using .NET you could use SignalR.

I hope it helps or at least it gives an idea to solve your problem.

Francisco Goldenstein
  • 13,299
  • 7
  • 58
  • 74