gpt4 book ai didi

azure - CancellationToken 不会在 Azure Functions 中触发

转载 作者:行者123 更新时间:2023-12-01 01:49:26 25 4
gpt4 key购买 nike

我有这个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com