Dave New
Dave New

Reputation: 40092

Upload blob and acquire lease in one transaction

Is it possible to upload to blob storage and acquire a lease on that blob within the same transaction. This would be to avoid a potential race condition.

The following code does the above but as two distinct transactions:

blob.UploadText(String.Empty);
blob.AcquireLease(TimeSpan.FromSeconds(60), leaseId);

If another thread/process/instance had to acquire a lease on that blob between the above two transactions, then a StorageException (HTTP code 412) would be thrown.

This can be mitigated by catching such exceptions, as shown below, but without being able to perform the upload and lease acquisition in one transaction we cannot guarantee that the blob will be leased by this thread after upload.

blob.UploadText(String.Empty);

try
{
    blob.AcquireLease(TimeSpan.FromSeconds(60), leaseId);
}
catch (StorageException ex)
{
    if (ex.RequestInformation.HttpStatusCode != 412)
    {
        throw;
    }
}

Upvotes: 0

Views: 937

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136336

AFAIK, it is not possible today to upload and acquire lease in just one transaction.

Looking at your code above, can't you put the blob.UploadText in the same try/catch block? That way upload operation by 2nd thread will fail if the 1st thread has acquired the lease. Also because these operations happen sequentially and not in parallel, more than likely the thread which uploaded the blob will acquire the lease. You will need to try it out though.

Upvotes: 1

Related Questions