1

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?

Josh M.
  • 26,437
  • 24
  • 119
  • 200

2 Answers2

2

You can check the IsClientConnected

    if (!Response.IsClientConnected){
        HttpContext.Current.Response.End();
        return;
    }
Aristos
  • 66,005
  • 16
  • 114
  • 150
  • 1
    Sure but that won't work during a long-running process. Say, for instance, the page is executing some SQL query and the user navigates away - it would be nice to catch that and kill the SqlConnection so the SQL server isn't processing the query in vain. – Josh M. Apr 14 '11 at 22:30
  • @Josh M. How long is the long ? 1 second ? 10 seconds ? that the SQL query takes to process ? Yes in general there is not a trigger to see if the user is not connected while you do thinks, other than this function. If you have too big works to do, you can check it time to time to avoid some long processing. – Aristos Apr 14 '11 at 22:33
  • @Josh Pages usually takes less than a second to make the process. The pages thats takes longer need special take care, maybe and a progress bar - and maybe checks like this one time to time. – Aristos Apr 14 '11 at 22:34
  • The query could take 3 seconds, 10 seconds, or longer - it just seems like (in general) it would be nice to be able to cancel the query if the user no longer cares about the results. – Josh M. Apr 14 '11 at 22:38
  • @Josh Can you check it every 2 seconds ? and if the user is not connect is stop it. (probably using a thread). – Aristos Apr 14 '11 at 22:40
  • Yeah that's the only way I can think to do it...maybe I will have to! – Josh M. Apr 14 '11 at 23:24
1

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