任务继续执行多项任务

VAA*_*AAA 3 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;

    });

}
Run Code Online (Sandbox Code Playgroud)

然后我有一个ListBox,我可以拖放多个文件,所以我想做的是在ListBox文件中做一个FOR LOOP然后调用UploadDocument();但是我想首先在listBox中上传第一个文件然后在完成后继续第二个文件档案等......

关于最佳方法的任何线索?

非常感谢.

Jon*_*eet 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]
}
Run Code Online (Sandbox Code Playgroud)

事实上,UploadDocument无论如何你都可以变得更简单:

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

async方法中包装它并不是特别有用.

(您可能希望将类型更改为不是string- 不清楚是什么_cloudDocuments.)

通常,您应该始终async返回一个方法,Task或者Task<T>除非必须使其返回void以符合事件处理模式.