从Session_Start调用异步方法 [英] Call Async Method from Session_Start

查看:90
本文介绍了从Session_Start调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Global.asax中的 Session_Start 调用异步方法?

How can I call an async method from Session_Start in Global.asax ?

Global.asax:

Global.asax:

    protected async Task Session_Start(object sender, EventArgs e)
    {            
        Session.Timeout = 10;

        // Do some asynch work
        await repository.SetStatsInfo(System.DateTime.Now);            
    }

异步方法:

    public async Task SetStatsInfo(DateTime time)
    {
        using (ApplicationDBContext db = new ApplicationDBContext())
        {
            // Do stuff (update visitors counter in db) ..

            await db.SaveChangesAsync();

        }
    }

我可以全部同步运行(定义 void Session_Start 等),该方法可以正常工作,但希望使用异步方式,以免击中数据库。

I can run it all synchronously (define void Session_Start etc.) which is working, but would prefer the async way so that hitting the db is not blocking.

像这样在 Session_Start 中使用'异步任务'运行,代码未执行, session_start 个断点$ c>没有被命中。

Running like this with 'async Task' for Session_Start, the code is not executed, breakpoints inside session_start are not hit.

推荐答案

诸如 Session_Start 这样的方法Global.asax是特殊的。您不能随便定义新的。该框架将运行其编程运行的框架,并且未提供异步版本。因此,永远不会运行异步版本。

Those methods like Session_Start in Global.asax are special. You can't just arbitrarily define new ones. The framework runs the one it's programmed to run, and no async versions are provided. As a result, no async version will ever be run.

但是,无论如何,异步实际上并没有任何意义。在启动和关闭应用程序池时调用Global.asax方法。结果,在任何时候都放弃工作线程是没有意义的,因为在完成工作之前,别无他法。

However, it doesn't really make sense to be async anyways. The Global.asax methods are called at startup and shutdown of the App Pool. As a result, it doesn't make sense to give up the operating thread at any point, because nothing else can happen until it completes its work anyways.

不能完全确定您在做什么,但是根据代码中的注释,听起来好像这不是正确的地方。同样,此代码仅运行一次,而不是每个请求运行一次。如果您希望每个请求发生某些事情,请查看类似操作过滤器的事情。

I'm not entirely sure what you're doing, but based on the comment in your code, it doesn't sound like this is the right place to be doing it anyways. Again, this code runs only once, not per request. If you want something to happen per request, look into something like an action filter.

这篇关于从Session_Start调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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