CancellationToken 不会在 Azure Functions 中触发 [英] CancellationToken doesn't get triggered in the Azure Functions

查看:18
本文介绍了CancellationToken 不会在 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.

这篇关于CancellationToken 不会在 Azure Functions 中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆