在Azure函数中不会触发CancellationToken [英] CancellationToken doesn't get triggered in the Azure Functions
问题描述
我有这个简单的Azure函数:
I've got this simple Azure Function:
public static class MyCounter
{
public static int _timerRound = 0;
public static bool _isFirst = true;
[FunctionName("Counter")]
//[TimeoutAttribute("00:00:05")]
public async static Task Run([TimerTrigger("*/10 * * * * *")]TimerInfo myTimer, TraceWriter log, CancellationToken token)
{
try
{
log.Info($"C# Timer trigger function executed at: {DateTime.UtcNow}");
if (_isFirst)
{
log.Info("Cancellation token registered");
token.Register(async () =>
{
log.Info("Cancellation token requested");
return;
});
_isFirst = false;
}
Interlocked.Increment(ref _timerRound);
for (int i = 0; i < 10; i++)
{
log.Info($"Round: {_timerRound}, Step: {i}, cancel request:{token.IsCancellationRequested}");
await Task.Delay(500, token).ConfigureAwait(false);
}
}
catch (Exception ex)
{
log.Error("hold on, exception!", ex);
}
}
}
我想做的是在应用停止或发生代码重新部署(主机关闭事件)时捕获CancellationToken请求事件.
What I'm trying to do is capturing the CancellationToken request event when the app stops or a code redeploy happened (host shutdown event).
顺便说一句,我也尝试过在for循环中检查IsCancellationRequested属性.永远不会成真.
BTW, I've also tried to check the IsCancellationRequested property in the for loop as well. Never turns true.
主要要求是在功能部署期间不要丢失任何操作/数据,我想知道该应用程序正在停止,因此一旦主机在更新后再次启动,我将保留一些要处理的数据.
The main requirement is not to loose any operation/data during the function deployments, I want to know that the app is being stopped so that I persist some data to be processed once host started again after update.
推荐答案
根据您的代码,我在我这边进行了测试,这是我的测试结果:
Based on your code, I tested it on my side, here are my test result:
从以上屏幕截图中,我们可以发现,除了第一轮以外,随后的几轮都无法处理取消回调.正如法比奥·卡瓦坎特(Fabio Cavalcante)所说,我删除了_isFirst
逻辑检查,发现它可以在所有回合中工作,如下所示:
From the above screenshots, we could find that the subsequent rounds could not handle the cancellation callback except the first round. As Fabio Cavalcante commented, I removed the _isFirst
logical checking and found it could work for all rounds as follows:
注意:我通过在触发TimerTrigger时禁用功能来模拟主机的关闭.
Note: I simulated the shutdown of my host by disabling my function when the TimerTrigger is triggered.
这篇关于在Azure函数中不会触发CancellationToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!