ASP.NET MVC使用异步Action的方法

在没有使用异步Action之前,在Action内,比如有如下的写法:

1
2
3
4
5
6
public ActionResult Index()
{
    CustomerHelper cHelper = new CustomerHelper();
    List<customer> result = cHelper.GetCustomerData();
    return View(result);
}</customer>

以上,假设,GetCustomerData方法是调用第三方的服务,整个过程都是同步的,大致是:

→请求来到Index这个Action
→ASP.NET从线程池中抓取一个线程
→执行GetCustomerData方法调用第三方服务,假设持续8秒钟的时间,执行完毕
→渲染Index视图

在执行执行GetCustomerData方法的时候,由于是同步的,这时候无法再从线程池抓取其它线程,只能等到GetCustomerData方法执行完毕。

这时候,可以改善一下整个过程。

→请求来到Index这个Action
→ASP.NET从线程池中抓取一个线程服务于Index这个Action方法
→同时,ASP.NET又从线程池中抓取一个线程服务于GetCustomerData方法
→渲染Index视图,同时获取GetCustomerData方法返回的数据

所以,当涉及到多种请求,比如,一方面是来自客户的请求,一方面需要请求第三方的服务或API,可以考虑使用异步Action。

假设有这样的一个View Model:

1
2
3
4
5
public class Customer
{
    public int Id{get;set;}
    public Name{get;set;}
}

假设使用Entity Framework作为ORM框架。

1
2
3
4
5
6
7
8
9
10
11
12
public class CustomerHelper
{
    public async Task<list>> GetCustomerDataAsync()
    {
        MyContenxt db = new MyContext();
        var query = from c in db.Customers
                    orderby c.Id ascending
                    select c;
        List<customer>  result = awai query.ToListAsycn();
        return result;             
    }
}</customer></list>

现在就可以写一个异步Action了。

1
2
3
4
5
6
public async Task<actionresult> Index()
{
    CustomerHelper cHelper = new CustomerHelper();
    List<customer> result = await cHlper.GetCustomerDataAsync();
    return View(result);
}</customer></actionresult>

Index视图和同步的时候相比,并没有什么区别。

1
2
3
4
5
@model List<customer>
@foreach(var customer in Model)
{
    <span>@customer.Name</span>
}</customer>

当然,异步还设计到一个操作超时,默认的是45秒,但可以通过AsyncTimeout特性来设置。

1
2
3
4
5
[AsyncTimeout(3000)]
public async Task<actionresult> Index()
{
    ...
}</actionresult>

如果不想对操作超时设限。

1
2
3
4
5
[NoAsyncTimeout]
public async Task<actionresult> Index()
{
    ...
}</actionresult>

综上,当涉及到调用第三方服务的时候,就可以考虑使用异步Action。async和await是异步编程的2个关键字,async总和Action

到此这篇关于ASP.NET MVC使用异步Action的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/asp-net/1254.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部