2017-08-24 80 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