15
votes

we have started using async/await in asp.net application, now we are getting the famous exception in our production

An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/376/ROOT

Process ID: 3796

Exception: System.NullReferenceException

Message: Object reference not set to an instance of an object.

StackTrace: at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext) at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext) at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state) at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask) --- End of stack trace from previous location where exception was thrown --- at System.Threading.Tasks.AwaitTaskContinuation.b__1(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch()

Is there any way we can get more information about the code/task that makes problem?

Second question: we tried to reproduce the exception locally in a simple test webform application

        protected void Page_Load(object sender, EventArgs e)
    {
        LogMessageToFile("before_task");
        var t = Test();

        tasks.Add(t);
    }
    async Task Test()
    {
        await Task.Run(() =>
       {
           LogMessageToFile("inside_task");
           Thread.Sleep(1000);
       }
            );
        this.Title = "test";
        LogMessageToFile("after_task");

        //  throw new Exception("");
    }

but we never get the exception in our test page seems that the code after await in Test function is never called and the tasks state are WaitingForActivation, why we do not get exception in this code?

1
try catch block araound await?Legends
this.Title = "test"; can be null if the page have gone and you do not take care about... to wait before the page gone.Aristos

1 Answers

18
votes

The legacy type (LegacyAspNetSynchronizationContext) in your call stack indicates that your web.config settings are incorrect. Set targetFramework to 4.5 or higher.

async/await cause undefined behavior on earlier versions of ASP.NET.

why we do not get exception in this code?

Because you probably updated the broken application to 4.5+ (which turned on "quirks mode", rendering await unusable), but created a new test application for 4.5+ (which turns off "quirks mode", allowing await to work).