Azure Function Cancellation Token not working

398 Views Asked by At

I would like to clean up resources (e.g. remove subscription) whenever a cancellation is sent to the program (e.g. ctrl+c when running locally or stopping the program)

However, the cancellation token does not seems to be working, nothing is being logged.

Below is my code:

       [FunctionName("MainFunction")]
        public static async Task Run(
            [TimerTrigger("0 */15 * * * *", RunOnStartup = true)] TimerInfo myTimer,
            ILogger log,
            CancellationToken cancellationToken)
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                cancellationToken.Register(() =>
                {
                    log.LogWarning("stoppping timer function");
                });

                await Task.Delay(8000, cancellationToken);

                List<dynamic> subscriptionList = await SendHttpReq(accessToken, cancellationToken);
            }
            catch (Exception ex)
            {
                log.LogWarning("Cancellation triggered");
            }
        }

I am testing it locally via visual studio. I am sending ctrl+c to the terminal once it start but "stoppping timer function" is not logged and only see Exception thrown: 'System.Threading.Tasks.TaskCanceledException' in System.Private.CoreLib.dll at the output box of visual studio when the program ends (i.e. when SendHttpReq is completed). enter image description here

Does CancellationToken gets triggered when the function is running or can be triggered anytime?

How can gracefully shutdown the function by cleaning up other resources before shutdown? Or is there any ways I can listen to host shutdown.

Thank you!

1

There are 1 best solutions below

0
SwethaKandikonda On

This is because when you hit ctrl+c the main thread receives the signal, decides to stop the debugger and waits for the timer to complete.

Also the logs will be seen in the terminal but not the output window.

For a graceful shutdown you can refer it from here.