In a legacy MVC 5 web app I want the user to be able to continue browsing after clicking a button which makes an ajax call to a long running action.
(Note: The action returns void
- I am not interested in the response)
When I click the button I am unable to make any other requests until the action completes.
Edit: Here is the ajax code:
$('#EmailReport') //
.click(function() {
$.ajax({
type: "POST",
url: '/Home/EmailReport',
complete: function() {console.log("done")},
async: true
});
});
Controller
[HttpPost]
public async Task EmailReport()
{
// for testing - sleep for 10 seconds
await Task.Delay(TimeSpan.FromSeconds(10));
}
Here is a screenshot in Chrome dev tools:
EmailReport
is the ajax call, the two requests at the bottom are me trying to browse to another page - as you can see the first request is pending
and any subsequent requests are cancelled
Does anyone have any ideas how I can resolve or troubleshoot this issue?
The problem is that, your action waits for completion of the task. Don't make it wait and return as soon as you start the task.
[HttpPost]
public void EmailReport()
{
// for testing - sleep for 10 seconds
var myTask = Task.Delay(TimeSpan.FromSeconds(10));
myTask.Start();
}
Your request is cancelled because it is a page redirect request and old page redirect requests are cancelled when a new one is issued (e.g. when you click a link 2 times, first click is ignored). It is the way browsers implement it. It is not related with the root of your problem.
The simplest way would be as follows :
Task t = new Task(() => TimeSpan.FromSeconds(10));
t.Start();
It is better to use Task as compared to thread for long running jobs to avoid core affinity and better CPU utilisation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With