Home > OS >  CancellationTokenSource callback is called for all request
CancellationTokenSource callback is called for all request

Time:12-09

In Startup.cs I set up a TimeOut class

app.UseMiddleware<AppTimeout>();

Then I set up a CancellationTokenSource with handler

public class AppTimeout
{
       public async Task Invoke(HttpContext httpContext, ILogger log)
       {
          
          var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(httpContext.RequestAborted);

          cancellationTokenSource.CancelAfter(myTimestamp);

           var path = httpContext.Request.Path;
           cancellationTokenSource.Token.Register(() =>
           {    
               log.info($"timeout path is {path}");
           });
           
           await _next(httpContext);
       }
}

My problem is if I have only one request in timeout , the callback of timeoutCancellationTokenSource.Token is called for all request that have been processed by Invoke methode, even request that already finished in correct time

Do you know why I encounter this behaviour and how to fix it please?

CodePudding user response:

using var registration = timeoutCancellationTokenSource.Token.Register(() => {    
    log.info($"timeout path is {path}");
});
// your other code here...

Now it will unregister correctly when complete, i.e. when leaving the scope of the using.

  • Related