Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.net 页面被关闭后,服务器端是否仍然执行中?

ASP.net 页面被关闭后,服务器端是否仍然执行中?2011-02-08问题:当一个正在执行中的ASPX页面执行到一半的时候,浏览器中你关闭了这个页面,服务器端对应的这个页面的代码仍然在执行么?

答案:除非你代码里面做了特殊判断,否则仍然正在执行。

注意点:

1、客户端显示页面的时候,后台已经执行完了的页面对象早已经不存在了。当然这时候谈不上服务器段执行不执行的问题了。

2、页面还没有返回,处于等待状态的时候。关闭ASPX页面,才会涉及到上面提到的服务器端仍然在执行的情况。

3、客户端关闭的时候根本不向服务器发送指令。

4、除非你代码里面做了特殊判断,这里的特殊判断指用 if(!Response.IsClientConnected) 来检测状态而用代码终止运行。

下面的简单代码就是演示关闭页面后,看是否仍然在执行?

你可以在这个页面打开后, 还没有返回任何信息的时候把这个页面关闭,然后看指定目录下是否有对应文件被创建并填写内容。

protected void Page_Load(object sender, EventArgs e)
{
StringBuilder txt = new StringBuilder();
txt.AppendLine();
txt.AppendLine(DateTime.Now.ToString("u"));
txt.AppendLine("asvd");
Response.Write(DateTime.Now.ToString("u"));
Response.Write(" ");
Thread.Sleep(50000);
txt.AppendLine(DateTime.Now.ToString("u"));
Response.Write(DateTime.Now.ToString("u"));
Response.Write(" ");
// 把一些信息写到另外一个文件,借此察看是否正在运行
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
DateTime dt = DateTime.Now;
string shortfileName = string.Format("errors_{0:0000}{1:00}{2:00}.log", dt.Year, dt.Month, dt.Day);
string fileName = Path.Combine(dir, shortfileName);
StreamWriter sw;
if (File.Exists(fileName))
sw = File.AppendText(fileName);
else
sw = File.CreateText(fileName);
sw.Write(txt.ToString());
sw.Close();
sw = null;
}

作了特殊判断的情况简单例子:

注意: IsClientConnected 的判断在 VS.net 开发工具自带的开发站点 ASP.NET Development Server 是不支持的。ASP.NET Development Server 永远返回 true 。

IIS 才是支持的。

protected void Page_Load(object sender, EventArgs e)
{
StringBuilder txt = new StringBuilder();
for (int i = 0; i < 100; i++)
{
if (this.Response.IsClientConnected)
{
txt.AppendLine();
txt.AppendLine(DateTime.Now.ToString("u"));
txt.AppendLine(i.ToString());
Response.Write(DateTime.Now.ToString("u"));
Response.Write(" ");
Thread.Sleep(500);
}
else
{
Response.End();
return;
}
}
txt.AppendLine(DateTime.Now.ToString("u"));
Response.Write(DateTime.Now.ToString("u"));
Response.Write(" ");
// 把一些信息写到另外一个文件,借此察看是否正在运行
string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
DateTime dt = DateTime.Now;
string shortfileName = string.Format("errors_{0:0000}{1:00}{2:00}.log", dt.Year, dt.Month, dt.Day);
string fileName = Path.Combine(dir, shortfileName);
StreamWriter sw;
if (File.Exists(fileName))
sw = File.AppendText(fileName);
else
sw = File.CreateText(fileName);
sw.Write(txt.ToString());
sw.Close();
sw = null;
}