asp.netpage-lifecycle

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


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?


Solution

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