这篇知识库文章说ASP.NET Response.End()
中止了线程。
Reflector显示如下:
public void End()
{
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
else if (!this._flushing)
{
this.Flush();
this._ended = true;
if (this._context.ApplicationInstance != null)
{
this._context.ApplicationInstance.CompleteRequest();
}
}
}
这对我来说似乎很严厉。如KB文章所述,应用程序中的任何后续代码Response.End()
都不会执行,这违反了最少惊讶的原则。这几乎就像Application.Exit()
在WinForms应用程序中一样。引起的线程中止异常Response.End()
无法捕获,因此将代码包围在try
... finally
中将无法满足。
这使我想知道我是否应该始终避免Response.End()
。
任何人都可以提出,我应该使用Response.End()
,当Response.Close()
,当HttpContext.Current.ApplicationInstance.CompleteRequest()
?
参考:Rick Strahl的博客条目。
根据我收到的输入,我的回答是,是,这Response.End
是有害的,但在某些情况下很有用。
- 使用
Response.End()
作为一个不可捕获抛出,立即终止HttpResponse
在特殊的条件。在调试过程中也很有用。 避免Response.End()
完成常规反应。 - 用于
Response.Close()
立即关闭与客户端的连接。根据此MSDN博客文章,此方法不适用于正常的HTTP请求处理。 您极不可能有充分的理由调用此方法。 - 用于
CompleteRequest()
结束正常请求。 当前事件完成后,CompleteRequest
导致ASP.NET管道跳到该EndRequest
事件HttpApplication
。因此,如果您致电CompleteRequest
,然后向响应中写入更多内容,则写入内容将发送给客户端。
编辑-2011年4月13日
进一步明晰,请访问:
- 有用的帖子在MSDN博客
- 由乔恩·里德有用的分析
Response.Redirect
并且Server.Transfer
两者都Response.End
应该避免。
Response.End
ThreadAbortException
很好。