ASP.NET:是否可以在Global.asax中调用异步任务? [英] ASP.NET: Is it possible to call async Task in Global.asax?

查看:127
本文介绍了ASP.NET:是否可以在Global.asax中调用异步任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Global.asax中的数据库上调用一些异步操作. 例如在Application_AuthenticateRequest中,我需要针对数据库对用户进行身份验证 异步任务有可能吗?

I need to call some async operations on my DB in Global.asax. for example in Application_AuthenticateRequest I need to Authenticate user against DB Is it possible with async Tasks?

推荐答案

现在有一种更简便的方法:

There's an easier way to do this now:

    public MvcApplication()
    {
        var wrapper = new EventHandlerTaskAsyncHelper(DoAsyncWork);
        this.AddOnAuthenticateRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
    }

    private async Task DoAsyncWork(object sender, EventArgs e)
    {
        var app = (HttpApplication)sender;
        var ctx = app.Context;

        ...
        await doSomethingAsync();
    }

使用这种方法,您可以使用async关键字定义一个方法,并使用'EventHandlerTaskAsyncHelper'类包装该方法以生成BeginEventHandler和EndEventHandler方法,以传递给AddOnAuthenticateRequestAsync调用.

With this approach, you define a method using the async keyword and wrap that method using the 'EventHandlerTaskAsyncHelper' class to generate BeginEventHandler and EndEventHandler methods to pass into the AddOnAuthenticateRequestAsync call.

这篇关于ASP.NET:是否可以在Global.asax中调用异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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