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()
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;
bool afterCancel = token.IsCancellationRequested;
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.
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
Yes, you re correct. Like function in Entity Framework : ReadToListAsync() and many more.ReplyDelete