CancellationToken 不会在 Azure Functions 中触发

aka*_*mis 6 azure azure-webjobs azure-functions

我有这个简单的 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是在应用程序停止或代码重新部署(主机关闭事件)时捕获 CancellationToken 请求事件。

顺便说一句,我还尝试检查 for 循环中的 IsCancellationRequested 属性。永远不会成真。

主要要求是在功能部署期间不要丢失任何操作/数据,我想知道应用程序正在停止,以便我在更新后再次启动主机时保留一些要处理的数据。

Bru*_*hen 3

根据您的代码,我在我这边进行了测试,这是我的测试结果:

在此输入图像描述

在此输入图像描述

从上面的截图中我们可以发现,除了第一轮之外,后续轮次都无法处理取消回调。正如 Fabio Cavalcante 评论的那样,我删除了_isFirst逻辑检查,发现它可以适用于所有回合,如下所示:

在此输入图像描述

注意:我通过在触发 TimerTrigger 时禁用我的函数来模拟主机的关闭。