【发布时间】:2014-01-10 11:16:03
【问题描述】:
在 asp.net 中执行 Response.End(); 方法时,它会抛出我在 catch 块中处理的 ThreadAbortException,在内部 catch 块结束后,我想执行一些进一步的代码,但它直接跳转到外部 catch 块。这是因为响应已经结束并且 .net 框架没有执行任何进一步的代码吗?
protected void btn_click(object sender, EventArgs e)
{
try
{
string fileToDownload = MapPath(@"~\Sample.txt");
string fileToRead = MapPath(@"~\FileNotExist.txt");
try
{
//Section 1
try
{
// try to read the file which does not exist to raise the exception
StreamReader ss = new StreamReader(fileToRead);
}
catch (IOException IoEx)
{
// Just for sample exception
}
// Section 2 code block still execute because exception handled by upper try catch block
//Section 2
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=SampleTemplate.txt");
Response.ContentType = "text";
Response.WriteFile(fileToDownload);
Response.Flush();
Response.End();
}
catch (System.Threading.ThreadAbortException abrtEx)
{
// do not treat this exception as Exception
}
//Section 3 Code block not executing even after exception handeled by ThreadAbortException
//Section 3
string test = "Do futher process after sample downloaded";
}
catch (Exception ex) // Outer Catch Block
{
throw ex;
}
}
【问题讨论】:
-
“样本下载后进行进一步处理”应该做什么?页面将完成其任务(提供下载文件。您希望它接下来做什么?
-
@Alexander:我只发布了我创建来解释我的场景的示例代码,真正的代码在下载之前和下载之后做了很多事情,我已经在我想要的 catch 块下完成了我们的 after doenload 代码纠正并移出捕获块。
-
我想了很多,是的,但我问的原因是我担心你使用页面生命周期错误。因此,对我来说,这是一个重要的问题。对于主页,在您结束响应后,它的生命就结束了。
-
是的,我明白了,但是在下载与页面生命周期无关的代码后,它会激活/停用某些服务并编写从其他来源收到的一些内容。我有其他解决方法,但首先我会尝试更正代码,如果可以的话