- 锁定Blob前必须检查Blob是否被另一个进程锁定。 在此之前,必须为Blob服务配置输入和输出文本框控件以进行Blob名称输入。
private async Task IsBlobLocked(CloudBlobContainer container, string blobName)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
try
{
AccessCondition accessCondition = new AccessCondition();
accessCondition.LeaseId = null;
await blockBlob.FetchAttributesAsync();
return false;
}
catch (StorageException ex)
{
if (ex.RequestInformation.HttpStatusCode == 404)
return false;
if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "LeaseIdMissing")
return false;
if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "BlobAlreadyLeased")
return true;
throw ex;
}
}
- 使用以下代码段锁定Blob并获取租约ID。
private async Task LockBlob(CloudBlobContainer container, string blobName)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
AccessCondition accessCondition = new AccessCondition();
accessCondition.LeaseId = null;
string leaseId = await blockBlob.AcquireLeaseAsync(TimeSpan.FromSeconds(30), null, accessCondition, null);
return leaseId;
}
- 释放Blob的租约。
private async Task ReleaseBlob(CloudBlobContainer container, string blobName, string leaseId)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
AccessCondition accessCondition = new AccessCondition();
accessCondition.LeaseId = leaseId;
await blockBlob.ReleaseLeaseAsync(accessCondition);
}