protected override async Task ExecuteAsync()

in src/DotNetWorker.ApplicationInsights/Initializers/AppServiceEnvironmentVariableMonitor.cs [34:74]


    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            bool changeDetected = false;

            foreach (string envVar in AppServiceOptionsInitializer.EnvironmentVariablesToMonitor)
            {
                string? currentVal = Environment.GetEnvironmentVariable(envVar);
                _monitoredVariableCache.TryGetValue(envVar, out string? cachedVal);

                if (!string.Equals(currentVal, cachedVal, StringComparison.Ordinal))
                {
                    changeDetected = true;
                    _monitoredVariableCache[envVar] = currentVal;
                }
            }

            if (changeDetected)
            {
                var oldTokenSource = Interlocked.Exchange(ref _cancellationTokenSource, new CancellationTokenSource());
                Interlocked.Exchange(ref _changeToken, new CancellationChangeToken(_cancellationTokenSource.Token));

                if (!oldTokenSource.IsCancellationRequested)
                {
                    oldTokenSource.Cancel();
                    oldTokenSource.Dispose();
                }
            }

            try
            {
                await Task.Delay(_refreshInterval, stoppingToken);
            }
            catch (OperationCanceledException)
            {
                // happens during normal shutdown
                break;
            }
        }
    }