返回带有async关键字的视图 [英] Returning a view with async keyword

查看:89
本文介绍了返回带有async关键字的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些代码示例中,我显示了如下所示的代码.

 public async Task<IActionResult> AddUser(User user)
 {
      ///Logic to add user
      return View();
 }

这是一种返回带有异步操作结果方法的视图的好方法,因为它本身不支持异步.

我在正常情况下检查了它的工作情况,但在哪些情况下它可能会失败或造成问题.

MSDN说(如果我没记错的话),asyncawait的使用是使您的Web应用程序可伸缩的好习惯.基本上,它有助于利用您的线程池,因此不必不一定分配1个线程来处理仅1 个请求.假设您执行以下操作:

 public async Task<IActionResult> AddUser(User user)
 {
      ///Logic to add user
      return await Task.Run(() => View());
 }

据说,在等待异步方法完成时,可以将线程分配给.NET运行时线程池全局队列中的另一个工作项(例如,另一个标记为异步的动作).这使得线程数可以少于需要处理的请求数.

async修饰符被标记为告诉.NET运行时这是可以应用上述机制的工作项.如果没有await内容,那么就性能或资源优化而言,它并没有多大帮助(如果我们不想说没什么").

为证明概念,我在HomeController中进行了以下操作:

    public async Task<ActionResult> FineGrained()
    {
        return await Task.Run(() => {
            return Json(Thread.CurrentThread.ManagedThreadId, JsonRequestBehavior.AllowGet);
        });
    }

    public async Task<ActionResult> CoarseGrained()
    {
        return await Task.Run(async () => {
            await Task.Delay(TimeSpan.FromSeconds(5));
            return Json(Thread.CurrentThread.ManagedThreadId, JsonRequestBehavior.AllowGet);
        });
    }

这是测试线程利用率的jquery脚本:

        $.when(
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/CoarseGrained'),
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/FineGrained')
        ).done(function (v1, v2, v3, v4, v5) {
            console.log(v1[0]);
            console.log(v2[0]);
            console.log(v3[0]);
            console.log(v4[0]);
            console.log(v5[0]);
        });

我得到的许多结果之一: 30 25 30 30 25

我多次刷新了包含测试脚本的页面,并且总是得到重复的线程ID.足以证明理论.

There are some code samples where I show some code like below.

 public async Task<IActionResult> AddUser(User user)
 {
      ///Logic to add user
      return View();
 }

Is this a good practice to return a view with async action result method as view result it self-does not support async.

I checked in normal scenarios it works perfectly fine but what are the scenarios where it might fail or create problems.

解决方案

The use of async and await is a good practice to make your web application scalable, said MSDN (if I remember correctly :)). Basically, it helps utilizing your thread pool so that 1 thread does not necessarily to be allocated to handle only 1 request. Suppose that you have this action:

 public async Task<IActionResult> AddUser(User user)
 {
      ///Logic to add user
      return await Task.Run(() => View());
 }

it's being said that while waiting for the async method to be completed, the thread will be available to be allocated for another work item (e.g another action marked as async) in the .NET run-time thread-pool global queue. This makes the number of threads can be less than the number of requests need handling.

The async modifier is marked to tell .NET run-time that this is a work item that can be applied mechanism mentioned above. Without await something, it doesn't help much (if we don't want to say "nothing") in terms of performance or resource optimization.

For proof of concept, I played with following actions in my HomeController:

    public async Task<ActionResult> FineGrained()
    {
        return await Task.Run(() => {
            return Json(Thread.CurrentThread.ManagedThreadId, JsonRequestBehavior.AllowGet);
        });
    }

    public async Task<ActionResult> CoarseGrained()
    {
        return await Task.Run(async () => {
            await Task.Delay(TimeSpan.FromSeconds(5));
            return Json(Thread.CurrentThread.ManagedThreadId, JsonRequestBehavior.AllowGet);
        });
    }

and this is the jquery script to test the thread utilization:

        $.when(
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/CoarseGrained'),
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/FineGrained'),
            $.getJSON('/Home/FineGrained')
        ).done(function (v1, v2, v3, v4, v5) {
            console.log(v1[0]);
            console.log(v2[0]);
            console.log(v3[0]);
            console.log(v4[0]);
            console.log(v5[0]);
        });

One of many results I got: 30 25 30 30 25

I refreshed the page containing the test script several times and always got repeat thread id. It's fair enough to prove the theory.

这篇关于返回带有async关键字的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆