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
}
async Task<T>call? Stephen Clearly has beaten into us that we must never callGetAwaiter()or.Resultbecause of the risk of deadlocks - so how can an ASP.NET Application'sGlobalApplication_Startmethod safely call an async method? - Dai