Reputation: 459
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).
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!
Upvotes: 0
Views: 547
Reputation: 8234
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.
Upvotes: 0