Tuesday, September 29, 2015

Cancel current HTTP thread on server from client



Yes, this is possible, if we gracefully handle server flow particularly in long running task. It’s obvious that your may not wait for a long running task in server. For example, you are running one long running select query and in middle user has cancel the http request. How to cancel? 

Simply press cross sign after or before address bar (based on browser) or If you refresh/navigate to another page, browser will automatically send one cancelation signal to current HTTP thread.
Let’s see, whether browser really cancel the current HTTP or not!

Here is my simple long running code.

public IActionResult Index()
        {
           
           System.Threading.Thread.Sleep(5000);
            return View();
        }

And in middle when of execution when I am just pressing cross sign, It’s getting cancel from browser’s





End. Now, Question is that, how to receive the signal in server and take decision accordingly? The implementation is very simple, just we need to pass CancellationToken parameter to action.

public IActionResult Index(CancellationToken token)
        {
           
            bool flag = token.IsCancellationRequested;

            System.Threading.Thread.Sleep(5000);

            bool afterCancel = token.IsCancellationRequested;


            return View();
        }

If you have some existing parameter, then add this at end of all parameter. Now, let’s run the example again. It’s showing false in flag variable when I am triggering HTTP.


Now, In time of Thread.Sleep() execution , I have cancelled the HTTP request and we are seeing that the afterCancel is flag is true now.





2 comments:

  1. You should probably pass the CancellationToken to the long running task. Otherwise the task cannot know if the request was cancelled and that itself should cancel execution.

    ReplyDelete
  2. Yes, you re correct. Like function in Entity Framework : ReadToListAsync() and many more.

    ReplyDelete