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

Here we will see how to solve one of the most common runtime error ““Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.””

This error may occur in the following scenario’s

1) Response.End
2) Response.Redirect
3) Server.Transfer

Reason for this exception occurrence is because page execution is stopped and sent to the Application_EndRequest event in the application’s event pipeline.

When we call Response.End method it stops the page execution and raises the EndRequest event and thus the line of code after Response.End is not executed. Same thing happens when we use Response.Redirect and Server.Transfer methods because both they both call Response.End internally.

When a call is made to destroy a thread, the CLR internally throws a ThreadAbortException. This is a exception that can be caught and handled explicitly.

Use a try-catch statement to catch the exception as below

 try  
 {  
 }  
 catch (System.Threading.ThreadAbortException)  
 {  
     //do nothing  
 }  

While using Response.Redirect we can use an overload of the same

 Response.Redirect(String url, bool endResponse);  

It passes false for endResponse parameter to suppress the internal call to Response.End

Use Server.Execute instead of Server.Transfer as the execution of code happens on the new page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s