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程序,建议都使用异步。因为异步可以提升系统的性能。准确来讲,不是提升性能,不会提高访问速度,而是提高服务器的“吞吐量”,也就是可以处理的并发请求数。

  • 相关阅读:
    HDU 1716 排列2
    HDU 3405 World Islands
    HDU 5624 KK's Reconstruction
    HDU 2689 Tree
    UVA 12075 Counting Triangles
    UVA 11100 The Trip, 2007
    [USACO 2004DEC] Navigation Nightmare
    [USACO 2017DEC] Barn Painting
    [Usaco2017 Dec] A Pie for a Pie
    [USACO 2017DEC] Greedy Gift Takers
  • 原文地址:https://www.cnblogs.com/dotnet261010/p/12344490.html
Copyright © 2011-2022 走看看