“Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”

This is one of the common runtime error reported by a lot of ASP.NET users.

Problem description

A successfully compiled code at runtime throws the following error during an operation:

“Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.”

Typically, this happens when the Response.EndResponse.Redirect, or Server.Transfer method is used.

Assessment

This happens because current page execution is stopped and execution is sent to the Application_EndRequest event in the application’s event pipeline.

The duty of Response.End method is to stop the page execution and raise the EndRequest event. Thus, the line of code that follows Response.End is not executed. Error occurs with Response.Redirect and Server.Transfer methods too because both the methods call Response.End internally.

When a call is made to the Abort method to destroy a thread, the CLR throws a ThreadAbortException. It is a special exception that can be caught, but will automatically be raised again at the end of the catch block. When this exception is re-raised, the CLR executes all the finally blocks before ending the thread.

Using Visual Studio debugger, we can see the internal message for the exception as “Thread was being aborted.”

Resolution

Try one of the following that suits your workflow:

  • Use a try-catch statement to catch the exception if needed
try { 
  // your code here
} 
catch (System.Threading.ThreadAbortException ex){ 
  // log/handle it
}
  • For Response.End:
    Invoke HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event
  • For Response.Redirect
    Use an overload,  Response.Redirect(String url, bool endResponse) that passes false for endResponse parameter to suppress the internal call to Response.End
Response.Redirect ("mynextpage.aspx", false);
  • For Server.Transfer
    Use Server.Execute method to bypass abort. When Server.Execute is used, execution of code happens on the new page, post which the control returns to the initial page, just after where it was called.

Refer:
Microsoft Support Article – 312629
MSDN: HttpResponse.Redirect Method
MSDN: HttpResponse.End Method
MSDN: ThreadAbortException Class
MSDN: HttpServerUtility.Execute Method

Conclusion

This is as designed. This exception has bad effect on Web application performance, which is why handling the scenario correctly is important.

Keep learning!

3 thoughts on ““Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”

Leave a Reply