6
votes

How can I call an async method from Session_Start in 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);            
    }

async method:

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

            await db.SaveChangesAsync();

        }
    }

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.

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

2
Chris said it correctly. There is no reason for this to be async, as it simply doesn't make sense. stackoverflow.com/a/38956850/2410379 - David Pine
@DavidPine But what should we do when we need to consume an API that is only available as a async Task<T> call? Stephen Clearly has beaten into us that we must never call GetAwaiter() or .Result because of the risk of deadlocks - so how can an ASP.NET Application's Global Application_Start method safely call an async method? - Dai

2 Answers

10
votes

From what I understand, ASP has a designated thread that is the ONLY thread that has access to the HttpContext.Current object, and in turn, access to the Session (HttpContext.Current.Session) much like the UI thread in windows applications. Therefore, performing a .Wait() or .Result in Session_Start callback will give you unknown results and/or deadlock the process.

There seems to be numerous ways to govern a Task's thread of execution, the primary one being specifying your task to run with a certain synchronization context via the TaskScheduler class https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(v=vs.110).aspx#Sync

However, since the Task class was designed to implement IAsyncResult, which comes from the APM (Asynchronous Programming Model) pattern, this makes Task backwards compatible with older APM pattern code (Which from what I understand ASP was originally built on). It takes a bit of integration work, though https://blogs.msdn.microsoft.com/mazhou/2011/10/04/the-asynchronous-programming-models/ (Standard APM).

.Net 4.5 introduced a nice Task wrapper (EventHandlerTaskAsyncHelper) to perform asynchronous actions utilizing the APM-style HttpApplication was built to support. It meets all the requirements to access the Session object, and execute correctly in the HttpApplication:

public override void Init()
{
    base.Init();
    //EventHandlerTaskAsyncHelper Wraps the task call in an APM-style BeginEventHandler, EndEventHandler
    var wrapper = new EventHandlerTaskAsyncHelper(AsyncSessionStart);
    this.AddOnAcquireRequestStateAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
}

private async Task AsyncSessionStart(Object sender, EventArgs evtArgs)
{       
    //The only caveat is we have to check IsNewSession to see if it was created in this call
    //This doesn't need to be applied for other AddOn*Async wire-ups
    if (!Session.IsNewSession)
        return;

    await doSomethingAsync();
}

//I recall seeing something that for session state to be active, this callback has to be declared, even if empty
protected void Session_Start(object sender, EventArgs e)
{
    //Synchronous session
}
4
votes

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.

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.