首页 > 解决方案 > Azure 持久功能 - 编排中的计数器

问题描述

我正在基于监视器模式构建一个持久功能。我有下面的代码,我的问题是关于我用于简单指数重试回退的计数器变量。

[FunctionName("RequestOrchestrator")]
public static async Task RequestOrchestrator(
    [OrchestrationTrigger] DurableOrchestrationContext monitorContext, ILogger log)
{
    DateTime endTime = monitorContext.CurrentUtcDateTime.AddHours(1);
    int counter = 0;

    while (monitorContext.CurrentUtcDateTime < endTime)
    {
        var result = await monitorContext.CallActivityAsync<bool>("GetStatusExternal", "test");

        if (result)
        {
            // all ok
            break;
        }
        else
        {
            counter++;
            // Wait for the next checkpoint with exponential backoff
            var nextCheckpoint = monitorContext.CurrentUtcDateTime.AddSeconds(5 * counter);
            if (!monitorContext.IsReplaying)
            {
                log.LogInformation($"Next check at {nextCheckpoint}.");
            }

            await monitorContext.CreateTimer(nextCheckpoint, CancellationToken.None);
        }
    }
}

计数器的使用是这样还是counter++需要进入

if (!monitorContext.IsReplaying)
  counter++;

它是重播安全的吗?

标签: c#azureazure-functionsazure-durable-functions

解决方案


不,你不需要monitorContext.IsReplaying到处检查counter++
您只需要对您只想运行一次的语句进行此检查,例如日志记录(如在您的代码中)、对外部系统的状态更新等。

为了重放安全,你基本上只需要你的代码是确定性的。因此,任何不能在纯函数中构成的代码都必须移到它们自己的活动函数中。其他一切都会做。

如文档所述,任何随时间变化(重放时间)的代码,如基于时间的生成器、来自外部 API 的远程数据等,都必须在活动函数中。


推荐阅读