2015-10-19 24 views
1

我正在使用Azure存儲來存儲和檢索圖像。我有這樣的方法來保存圖像(BLOB):Azure存儲 - 此代碼的任何時間問題?

public void SaveBlob(string containerName, string blobName, byte[] blob) 
{ 
    // Retrieve reference to the blob 
    CloudBlockBlob blockBlob = GetContainer(containerName, true).GetBlockBlobReference(blobName); 

    using (var stream = new MemoryStream(blob, writable: false)) 
    { 
     blockBlob.UploadFromStream(stream); 
    } 
} 

這是GetContainer方法:

public CloudBlobContainer GetContainer(string containerName, bool createIfNotExist) 
    { 
     if (string.IsNullOrEmpty(containerName)) 
      return null; 

     // Retrieve a reference to a container. If container doesn't exist, optionally create it. 
     CloudBlobContainer container = this._blobClient.GetContainerReference(containerName); 
     if (container == null && !createIfNotExist) 
      return null; 

     // Create the container if it doesn't already exist. It will be private by default. 
     container.CreateIfNotExists(BlobContainerPublicAccessType.Off, null, null); 

     return container; 
    } 

這裏發生的事情是,當我試圖保存一個blob,我得到一個參考首先是一個容器。如果容器不存在,則創建該容器,然後保存該blob。如果我必須先創建容器然後立即保存一個blob,我會在這裏遇到計時問題嗎?我擔心的是,在Azure完成創建之前,我可能會嘗試將Blob保存到容器中。或者,也許這不是一個問題?

回答

2

看着你的代碼,我不認爲你會遇到任何時間問題,因爲CreateIfNotExists方法是一個同步方法,並且只會在容器創建時返回。此外,對於Azure Blob存儲(與Amazon S3不同),該方法將立即創建容器,或者如果未能這樣做(或者換言之,Azure存儲爲Strongly Consistent),則會拋出錯誤。

此外我認爲這一段代碼是冗餘:

if (container == null && !createIfNotExist) 
      return null; 

container如將永遠等於null因此本if條件永遠不會是true

+0

你說容器永遠不會等於null。如果容器還不存在,它會是什麼? –

+0

當你調用'GetContainerReference'時,它不會進行網絡調用來檢查容器是否存在。它只是創建一個'CloudBlobContainer'對象的實例。然後,您可以對該對象執行操作,並且這些操作(如'CreateIfNotExists')將進行網絡調用。 –

+0

啊,我現在看到了。我需要調用CloudBlobContainer上的Exists方法來查看容器是否存在。 –