private async Task <LeaseResult> TryAcquireAsync(CloudBlockBlob blob, TimeSpan leaseTime, CancellationToken cancellationToken) { if (leaseTime < MinLeaseTime || leaseTime > MaxLeaseTime) { throw new ArgumentOutOfRangeException( nameof(leaseTime), "The lease time must be between 15 and 60 seconds, inclusive."); } try { var leaseId = await blob.AcquireLeaseAsync( leaseTime : leaseTime, proposedLeaseId : null, accessCondition : null, options : null, operationContext : null, cancellationToken : cancellationToken); return(LeaseResult.Success(leaseId)); } catch (StorageException ex) when(ex.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.Conflict) { // The lease has already been acquired by someone else. return(LeaseResult.Failure()); } }
private async Task <LeaseResult> TryCreateAndAcquireAsync(CloudBlockBlob blob, TimeSpan leaseTime, CancellationToken cancellationToken) { try { // Use an empty blob for the lease blob. The contents are not important. Only the lease state (managed // by Azure Blob Storage) is important. await blob.UploadFromByteArrayAsync( Array.Empty <byte>(), index : 0, count : 0, cancellationToken : cancellationToken); return(await TryAcquireAsync(blob, leaseTime, cancellationToken)); } catch (StorageException ex) when(ex.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed) { // The file has already created and leased by someone else. return(LeaseResult.Failure()); } }