Visual Studio报错:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值

异常:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值

原因:
使用了Response.End()方法,该方法会执行Thread.CurrentThread.Abort()操作,如果将Response.End()放在try-catch中,将会捕捉到Thread.CurrentThread.Abort()产生的ThreadAbortException 异常。

Response.End()方法:将当前所有缓冲的输出发送到客户端,停止该页的执行,并引发 EndRequest 事件。不会继续执行后面的代码。

对于一次的http request,web服务器会返回流。若不采用Response.End()结束,则会返回一整个页面,而得不到所需要的结果。

解决方案:可采用以下两种方法解决

1、在catch中排除ThreadAbortException异常,示例代码:

try
{
    Response.Write("Hello!");
    Response.End();
}
catch (System.Threading.ThreadAbortException)
{
}
catch (Exception ex)
{
    Response.Write(ex);
}
View Code

2、用Context.ApplicationInstance.CompleteRequest()结束当前请求(会继续执行后面的代码),示例代码:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        Response.Write("Hello world!");
        this.Page.Visible = false;
        Context.ApplicationInstance.CompleteRequest();
    }
    catch (Exception ex)
    {
        Response.Write(ex);
    }
}
View Code
原文地址:https://www.cnblogs.com/luswei/p/6485119.html