Asynchronous jquery call for async mvc controller

How do I get my jquery methods to call my mvc controller and my mvc controller to do two things at once?

Jquery code works fine. He just calls methods and keeps moving as I want.

$(document).ready(function () { console.log("1"); getADsad(); console.log("2"); lala(); console.log("3"); }); function getADsad() { $.ajax({ url: '/Configurator/Configure/Hello1', type: 'POST', dataType: 'json', success: function (data) { console.log(data + "hello1"); } }); } function lala() { $.ajax({ url: '/Configurator/Configure/Hello2', type: 'POST', dataType: 'json', success: function (data) { console.log(data + "hello2"); } }); 

My C # code, on the other hand, does not do two things at a time:

  [HttpPost] public async Task<LoginViewModel> Hello1() { var str = await GetSlowstring(); return str; } [HttpPost] public async Task<LoginViewModel> Hello2() { var str = await GetSlowstring(); return str; } public async Task<LoginViewModel> GetSlowstring() { await Task.Delay(10000); LoginViewModel login = new LoginViewModel(); login.UserName = "HejsN"; return await Task.FromResult(login); } 

The combined call should take a little more than 10 seconds if it is made correctly, but now it accepts a double.

Do I need to create a new thread for calls? Or is this done automatically by the application?

EDIT: enter image description here

+7
c # asynchronous asp.net-mvc
source share
3 answers

Based on the image of the Chrome console, a problem occurs in SessionState. By default, when an application uses SessionState, the ASP environment processes requests from one user sequentially (to prevent session variables from potential damage).

In cases where you want to enable parallel processing of requests for one user (and you do not need to update the session), you can use the SessionState attribute on the controller.

  [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)] 

More information can be found here: http://www.stefanprodan.com/2012/02/parallel-processing-of-concurrent-ajax-requests-in-asp-net-mvc/

+12
source share

You do not call await in your GetSlowstring method, so it synchronously blocks the thread using Thread.Sleep(10000); . For testing purposes, you can try replacing this line of code with the Task.Delay method (see the MSDN article for this method ):

 public async Task<string> GetSlowstring() { await Task.Delay(10000); return "hejsan"; } 

enter image description here

+1
source share

How to create two tasks in MVC?

 var t1 = new Task(() => { /*The slow task 1 */ }); var t2 = new Task(() => { /*The slow task 2 */}); Task.WaitAll(t1,t2); 
0
source share

All Articles