5

I'm doing some research on Cancelling Async Requests through WebAPI,

Recently I discovered that latest version of WebApi(not .NET-Core's), supports cancellation tokens. As a test I've written this code.

[HttpGet]
[Route("LongRequest")]
public async Task<string> VeryLongRequest(string Key, CancellationToken token)
{
    for (int i = 0; i < 5; ++i)
    {
        if (false == token.IsCancellationRequested)
        {
            Thread.Sleep(5000);
        }
        else
        {
            Trace.WriteLine("Cancelled");
        }
    }

    return "Complete";
}

This code works, and the cancellation token is updated, when a user closes the window/refreshes/ or navigates to a new page (Not on an SPA).

Being that HTTP Request's are suppose to be stateless, How is the cancellation mapping back to the request?

And how can I Manually Invoke a cancellation from my client?

johnny 5
  • 19,893
  • 50
  • 121
  • 195
  • 1
    I suppose it just triggered by asp.net when it detects connection was closed. So client side can affect this only by closing connection. – Evk Dec 07 '17 at 19:51
  • @Evk, I think its trigger from a FIN or Reset from the TCP connection, but I'm not sure. I'm not sure how I could manually invoke that though – johnny 5 Dec 07 '17 at 19:53
  • Well that's about the same as I told I think. And you cannot manually invoke it from client (except aborting connection of course). – Evk Dec 07 '17 at 19:54
  • But if you are using ajax - you can abort it when user presses button for example (there is abort() method), if that is what you mean by manually invoke cancellation from client. – Evk Dec 07 '17 at 20:03
  • @Evk thanks for the help. That info seems to be right to the best of my knowledge, if you post that as an answer I’ll mark it correct. – johnny 5 Dec 07 '17 at 21:34

0 Answers0