azure - CancellationToken 不会在 Azure Functions 中触发

标签 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);
        }
    }
}

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

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

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

最佳答案

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

enter image description here

enter image description here

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

enter image description here

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

关于azure - CancellationToken 不会在 Azure Functions 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746876/

相关文章:

Azure DevOps 管道定义 : How to switch between GUI and yml views

c# - 如何在azure webjob或函数中触发多个eventhub

azure - 从网络作业访问网站连接字符串

Azure WebJob/Scheduler 从上午 8 点到下午 6 点每 30 分钟一次?

时间:2019-03-17 标签:c#AzureFunctions分离html和css

c# - Azure 存储 Blob 重命名

caching - Windows Azure 是否具有 Web 缓存功能?

c# - MediatR 共享 TableBatchOperation 以在不同的处理程序中进行事务保存

c# - 实时遥测不适用于 Azure Function .NET Core 6

Azure函数并发: maxConcurrentRequests - is it Truly parallel to give a simultaneous execution of all requests happening at the same time