开发者

ASP.Net: How to stop page execution when browser disconnects?

开发者 https://www.devze.com 2023-02-24 16:57 出处:网络
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

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 s开发者_运维百科top the page from executing?


You can check the IsClientConnected

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


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.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号