private async Task KeepRenewingLease(BlobLeaseManager leaseManager, string leaseId, CancellationToken token) { var renewOffset = new Stopwatch(); while (!token.IsCancellationRequested) { try { // Immediately attempt to renew the lease // We cannot be sure how much time has passed since the lease was actually acquired renewOffset.Restart(); var renewed = await leaseManager.RenewLeaseAsync(leaseId, token); renewOffset.Stop(); if (!renewed) { return; } // We delay based on the time from the start of the last renew request to ensure var renewIntervalAdjusted = RenewInterval - renewOffset.Elapsed; // If the adjusted interval is greater than zero wait for that long if (renewIntervalAdjusted > TimeSpan.Zero) { await Task.Delay(RenewInterval - renewOffset.Elapsed, token); } } catch (OperationCanceledException) { leaseManager.ReleaseLease(leaseId); return; } } }