任务继续执行多项任务

时间:2013-02-27 15:25:47

标签: c# task-parallel-library async-await

我有一个方法可以将一个文件上传到服务器。现在除了方法上的任何错误编码之外还在工作(我是Task的新手)。

以下是将文件上传到服务器的代码:

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,我可以拖动&amp;删除多个文件所以我想要做的是在ListBox文件中执行FOR LOOP然后调用UploadDocument();但我想先在listBox中上传第一个文件,然后在完成后继续第二个文件,依此类推。 ..

有关最佳方法的任何线索吗?

非常感谢。

1 个答案:

答案 0 :(得分:9)

您应该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遵守事件处理模式。

相关问题