zoukankan      html  css  js  c++  java
  • ASP.NET MVC与TPL

    一、MVC中使用异步

    1、MVC中如何使用异步

    我们新建一个MVC的项目,我们在Home控制器的Index方法里面读取一个文件的内容,然后返回给用户,我们看下面的代码:

    /// <summary>
    /// 异步方法
    /// </summary>
    /// <returns></returns>
    public  Task<ActionResult> Index()
    {
        return Task.Run<ActionResult>(() => {
            using (StreamReader sr = new StreamReader("F:	est.txt"))
            {
                string txt = sr.ReadToEnd();
                return Content(txt);
            }
        });
    }

    我们可以得出结论:如果要在MVC中使用异步方法,只需要将返回值改为Task<ActionResult>即可,如果方法标记为async,连自己创建Task都可以省略:

    /// <summary>
    /// 异步方法,并使用async标注
    /// </summary>
    /// <returns></returns>
    public async Task<ActionResult> Index()
    {
        using (StreamReader sr = new StreamReader("F:	est.txt"))
        {
            string txt =await sr.ReadToEndAsync();
            return Content(txt);
        }
            //return View();
    }

    2、MVC中使用异步提升性能

    现在开发ASP.NET MVC程序,建议都使用异步。因为异步可以提升系统的性能。准确来讲,不是提升性能,不会提高访问速度,而是提高服务器的“吞吐量”,也就是可以处理的并发请求数。

  • 相关阅读:
    HDU1050
    POJ3528移石头
    CodeForces230A
    lca学习题
    rmq的st算法模板题 nyoj 119
    rmq问题和lca可以相互转化
    rmq算法,利用倍增思想
    poj 1274 基础二分最大匹配
    hdu 1520 树形dp入门题
    poj 1466 最大独立集
  • 原文地址:https://www.cnblogs.com/dotnet261010/p/12344490.html
Copyright © 2011-2022 走看看