0
votes

I've got a DotNet Core 2.2 api endpoint that accepts a CancellationToken and periodically checks it while processing. When I call that endpoint from my Angular 7 front end, then cancel the request (by unsubscribing), the cancellation token doesn't reflect the cancelled status. Is there a step I'm missing in order for the token to be cancelled correctly? Or is this totally not now the request cancelling process works?

Note that I can see the initial request fire, the api doing work, and the request cancelling (via the Chrome devtools Network tab).

Angular 7

private sub: Subscription;
doWork(): void {
  // calls to http client, sending a POST
  this.sub = this.service.doWork([1,2,3,4]).subscribe();
}
cancelWork(): void {
  if(this.sub && !this.sub.closed) {
    this.sub.unsubscribe();
  }
}

API

[HttpPost("DoWork")]
public async Task<ActionResult<HttpResponseMessage>> DoWork([FromBody] List<int> ids, CancellationToken cancellationToken)
{
    foreach(var id in ids)
    {
        // ---> cancellationToken.IsCancellationRequested is always false   <-------
        cancellationToken.ThrowIfCancellationRequested();

        await doLongRunningTask(id);
    }
}
1

1 Answers

0
votes

cancellationToken.ThrowIfCancellationRequested(); throws if the request was canceled by the moment of evaluating this line so it just won't work in your case. usually some async utils provide APIs for passing that token that they will use internally