ASP.Net:浏览器断开连接时如何停止页面执行?

发布于 2024-11-01 05:55:26 字数 136 浏览 1 评论 0原文

如果浏览器请求 ASP.Net 页面,然后用户单击“停止”或导航离开,我认为浏览器将关闭连接,ASP.Net 可能会停止执行。我认为情况并非如此,因为当我测试这个时,没有调用 Dispose() 。是否有办法知道浏览器/客户端何时断开连接,然后停止页面执行?

If a browser requests an ASP.Net page and then the user clicks "stop" or navigates away, I thought that the browser would close the connection and ASP.Net would perhaps stop execution. I don't think that's the case since Dispose() is not called when I test this. Is there anyway to know when the browser/client has disconnected and then stop the page from executing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

演多会厌 2024-11-08 05:55:26

我刚刚遇到这个非常古老的问题。

现在有一个巧妙的解决方案。从 .NET 4.5 开始,当客户端断开连接时,您实际上可以异步收到通知。

这意味着您可以终止长时间运行的 sql 查询。

操作方法如下:

private CancellationTokenRegistration _clientDisconnectRegistration;

private void StartListeningForClientDisconnected() {
  _clientDisconnectRegistration = HttpContext.Current.Response.ClientDisconnectedToken.Register(HttpClientDisconnected);
}

private void StopListeningForClientDisconnected() {
  _clientDisconnectRegistration.Dispose();
}

private void HttpClientDisconnected()
{
  // Here you can check if an active SQL query needs to be aborted
  // and if necessary, open a second connection to the DB and kill it.
}

I just came across this very old question.

There is a neat solution now. Since .NET 4.5 you can actually get notified asynchroneously when the client disconnects.

This means that you can kill the long-running sql query.

Here's how to do it:

private CancellationTokenRegistration _clientDisconnectRegistration;

private void StartListeningForClientDisconnected() {
  _clientDisconnectRegistration = HttpContext.Current.Response.ClientDisconnectedToken.Register(HttpClientDisconnected);
}

private void StopListeningForClientDisconnected() {
  _clientDisconnectRegistration.Dispose();
}

private void HttpClientDisconnected()
{
  // Here you can check if an active SQL query needs to be aborted
  // and if necessary, open a second connection to the DB and kill it.
}
旧时光的容颜 2024-11-08 05:55:26

您可以检查IsClientConnected

    if (!Response.IsClientConnected){
        HttpContext.Current.Response.End();
        return;
    }

You can check the IsClientConnected

    if (!Response.IsClientConnected){
        HttpContext.Current.Response.End();
        return;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文