我有这个简单的 Azure 函数:
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 请求事件。
顺便说一句,我也尝试检查 for 循环中的 IsCancellationRequested 属性。永远不会变成真的。
主要要求是在功能部署期间不要丢失任何操作/数据,我想知道应用程序正在停止,以便在更新后主机再次启动时保留一些要处理的数据。
根据您的代码,我在我这边进行了测试,这是我的测试结果:
从上面的截图中我们可以发现,除了第一轮之外,后续轮次都无法处理取消回调。正如 Fabio Cavalcante 评论的那样,我删除了_isFirst
逻辑检查发现它可以适用于所有回合,如下:
Note:我通过在触发 TimerTrigger 时禁用我的函数来模拟主机的关闭。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)