async Task GrabLeaseOrWait(BlobLeaseWrapper leaseWrapper, CancellationToken token) { // Try to acquire the blob lease, otherwise wait for some time before we can try again. var leaseId = await TryAcquireLeaseOrWait(leaseWrapper, token); if (string.IsNullOrEmpty(leaseId)) { return; } // Create a new linked cancellation token source, so if either the // original token is canceled or the lease cannot be renewed, // then the leader task can be canceled. using (var cts = CancellationTokenSource.CreateLinkedTokenSource(new[] { token })) { // Run the leader task. var leaderTask = _leaderTask.Invoke(cts.Token, _blob); // Keeps renewing the lease in regular intervals. // If the lease cannot be renewed, then the task completes. var renew = KeepRenewingLease(leaseWrapper, leaseId, cts.Token); // When any task completes (either the leader task or when it could // not renew the lease) then cancel the other task. await CancelAllWhenAnyCompletes(leaderTask, renew, cts); } }