Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I browse to other pages after making an ajax call?

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:

Ajax request

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?

like image 541
Vinyl Warmth Avatar asked Oct 19 '22 01:10

Vinyl Warmth


2 Answers

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.

like image 128
Gokhan Kurt Avatar answered Oct 20 '22 16:10

Gokhan Kurt


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.

like image 39
Rahul Jain Avatar answered Oct 20 '22 16:10

Rahul Jain