任务继续执行多个任务

问题描述:

我有一种方法将一个文件上传到服务器。现在正在工作,除了方法上的任何不好的编码(Im新任务库)。任务继续执行多个任务

这里是文件上载到服务器的代码:

private async void UploadDocument() 

{ 
    var someTask = await Task.Run<bool>(() => 
    { 
     // open input stream 
     using (System.IO.FileStream stream = new System.IO.FileStream(_cloudDocuments[0].FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
     { 
      using (StreamWithProgress uploadStreamWithProgress = new StreamWithProgress(stream)) 
      { 
       uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged; 

       // start service client 
       SiiaSoft.Data.FieTransferWCF ws = new Data.FieTransferWCF(); 

       // upload file 
       ws.UploadFile(_cloudDocuments[0].FileName, (long)_cloudDocuments[0].Size, uploadStreamWithProgress); 

       // close service client 
       ws.Close(); 
      } 
     } 

     return true; 

    }); 

} 

然后我有一个列表框,我可以拖动&中的多个文件所以我想要做的就是到ListBox中做一个for循环文件,然后拨打电话UploadDocument();,但我想先上传listBox中的第一个文件,然后完成后继续第二个文件等等...

任何线索的最佳方法呢?

非常感谢。

您应该让您的UploadDocument返回Task。然后你可以等待循环中的任务。例如:

private async Task UploadAllDocuments() 
{ 
    string[] documents = ...; // Fetch the document names 

    foreach (string document in documents) 
    { 
     await UploadDocument(document); 
    } 
} 

private async Task UploadDocument(string document) 
{ 
    // Code as before, but use document instead of _cloudDocuments[0] 
} 

事实上,你的UploadDocument可制成反正简单:

private Task UploadDocument() 
{ 
    return Task.Run<bool>(() => 
    { 
     // Code as before 
    }); 
} 

包装,在一个async方法不是特别有用。

(您可能想将类型更改为不string - 目前还不清楚是什么_cloudDocuments是)

在一般情况下,你应该始终做出async方法的返回TaskTask<T>除非你以使其返回void以符合事件处理模式。

+0

我只是这样做,一个问题..当我调用UploadAllDocuments();其下划线为绿色,当我悬停时,我得到:“因为这个调用没有等待,在调用前继续执行当前的方法......”任何线索? – VAAA 2013-02-27 16:31:32

+0

@VAAA:好的,我们没有任何关于你从哪里调用的内容......我们甚至不知道这是什么类型的应用程序...所以我不能真正帮助你的代码没有显示。 – 2013-02-27 16:46:40

+0

它是一个桌面应用程序,并通过点击一个按钮调用UploadAllDocuments()。 – VAAA 2013-02-27 16:48:06