0

I used to implement Sync actions in web api applications, and to get data asynchronously I used AJAX in the client part to get datas from api actions.

Then I read about async controller , I need to know the lifecycle to render a page

For example :

 public async Task<ActionResult> PWGasync()
    {
        ViewBag.SyncType = "Asynchronous";
        var widgetService = new WidgetService();
        var prodService = new ProductService();
        var gizmoService = new GizmoService();

        var widgetTask = widgetService.GetWidgetsAsync(); 
         await Task.Run(widgetTask);

        var pwgVM = new ProdGizWidgetVM( widgetTask.Result  );

        return View("PWG", pwgVM);
    }

did the view will be rendred first and then the data will be displayed?

6
  • No. The view will be rendered after all tasks are completed so that all results needed for rendering are available. Commented Nov 18, 2016 at 11:50
  • Lifecycle of an ASP.NET MVC 5 Application Commented Nov 18, 2016 at 12:00
  • @AndriyTolstoy what is the difference then between async and sync action ? Commented Nov 18, 2016 at 13:15
  • 1
    In this example the advantage is that all three tasks will be executed parallel each in its own thread and not one after another, so that the entire result needed for rendering could be retrieved faster. Commented Nov 18, 2016 at 13:40
  • @AndriyTolstoy yes in this example you are right. But generally parallelism is not async it is two different concepts. I mean if no parallelism exists (for exemple i'm waiting for only a task). what is the benefits of async action if the page is still not rendred until the task will be finished Commented Nov 18, 2016 at 15:52

1 Answer 1

1

did the view will be rendred first and then the data will be displayed?

No. async does not change the HTTP protocol. There is still one request and one response.

what is the difference then between async and sync action ?

async actions allow the request thread to return to the thread pool while the await operation is in progress. This makes better use of the thread pool, which in turn allows much better scalability of the web service.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, you mentionned "which in turn allows much better scalability of the web service" in the example the action will return a view not datas so I don't see any need for using async action .
@LamloumiAfif: What the action returns is immaterial. async is about freeing up threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.