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

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

问题描述

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

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 的 'async Task' 运行,代码不会被执行,session_start 内的断点未命中.

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

推荐答案

那些像 Global.asax 中的 Session_Start 这样的方法是特殊的.你不能随意定义新的.该框架运行其编程运行的框架,并且不提供异步版本.因此,不会运行任何异步版本.

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天全站免登陆