2017-08-24 81 views
3

我有以下兩個任務的示例。第一個完成時,第二個應該使用第一個結果。我在這個領域II新,如果有人指導我如何IT連鎖將不勝感激:連鎖繼續與任務

public async Task<string> UploadFile(string containerName, IFormFile file) 
    { 
     //string blobPath = ""; 
     var container = GetContainer(containerName); 
     var fileName = file.FileName; 
     CloudBlockBlob blob = container.GetBlockBlobReference(fileName); 
     using (var memoryStream = new MemoryStream()) 
     { 
      // await file.CopyToAsync(memoryStream); 
      // await blob.UploadFromStreamAsync(memoryStream); 

      // upload only when the 'memoryStream' is ready 
      Task.Factory.StartNew(() => file.CopyToAsync(memoryStream)) 
       .ContinueWith(m => blob.UploadFromStreamAsync(m.Result)); // ?? 
     } 
     return blob.Uri.AbsoluteUri; 
    } 

如果沒有第二方案:

public string UploadFile(string containerName, IFormFile file) 
{ 
    var container = GetContainer(containerName); 
    var fileName = file.FileName; 
    CloudBlockBlob blob = container.GetBlockBlobReference(fileName); 
    using (var memoryStream = new MemoryStream()) 
    { 
     file.CopyToAsync(memoryStream).Wait(); 
     blob.UploadFromStreamAsync(memoryStream).Wait(); 

     //Task.Factory.StartNew(() => file.CopyToAsync(memoryStream)) 
     // .ContinueWith(m => blob.UploadFromStreamAsync(m.Result)); // ?? 
    } 
    return blob.Uri.AbsoluteUri; 
} 
+2

要小心你的memoryStream生命週期,它會在你的第一個任務完成之前處理。 – GhostTW

回答

3

IFormFile獲取流,並直接上傳

public async Task<string> UploadFile(string containerName, IFormFile file) 
{ 
    //string blobPath = ""; 
    var container = GetContainer(containerName); 
    var fileName = file.FileName; 
    CloudBlockBlob blob = container.GetBlockBlobReference(fileName); 
    await blob.UploadFromStreamAsync(file.OpenReadStream()) 
    return blob.Uri.AbsoluteUri; 
} 
+0

效果不錯,在我的變體中是'blob.UploadFromStreamAsync(file.OpenReadStream())。Wait();'非常感謝,但是你能否解釋一下在將來如何使用ContinueWith? – Serge

+2

@Serge不會混合異步/等待和阻塞調用('.Result'或'.Wait()'),否則您將面臨死鎖的風險。讓代碼一直流動到異步 – Nkosi

+2

@Serge大多數情況下,您不應該使用ContinueWith。 – mason