'await'运算符只能与async lambda表达式一起使用

abh*_*ash 13 c# async-await .net-4.5

我正在尝试将文件列表复制到目录中.我正在使用async/await.但是我一直在收到这个编译错误

'await'运算符只能在异步lambda表达式中使用.考虑使用'async'修饰符标记此lambda表达式.

这就是我的代码

async Task<int> CopyFilesToFolder(List<string> fileList, 
            IProgress<int> progress, CancellationToken ct)
{
    int totalCount = fileList.Count;
    int processCount = await Task.Run<int>(() =>
    {
        int tempCount = 0;
        foreach (var file in fileList)
        {
            string outputFile = Path.Combine(outputPath, file);

            await CopyFileAsync(file, outputFile); //<-- ERROR: Compilation Error 

            ct.ThrowIfCancellationRequested();
            tempCount++;
            if (progress != null)
            {
                progress.Report((tempCount * 100 / totalCount)));
            }

        }

        return tempCount;
    });
    return processCount;
}


private async Task CopyFileAsync(string sourcePath, string destinationPath)
{
    using (Stream source = File.Open(sourcePath, FileMode.Open))
    {
        using (Stream destination = File.Create(destinationPath))
        {
            await source.CopyToAsync(destination);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

请问有谁可以指出我在这里缺少什么?

Ste*_*ary 30

int processCount = await Task.Run<int>(() =>
Run Code Online (Sandbox Code Playgroud)

应该

int processCount = await Task.Run<int>(async () =>
Run Code Online (Sandbox Code Playgroud)

请记住,lambda只是定义方法的简写.所以,你的外部方法是async,但在这种情况下,你试图await在lambda中使用(这是一种你的外部方法不同的方法).所以你的lambda也必须被标记async.

  • 抱歉,我不清楚:`Task.Run` 似乎通常用于卸载一些东西,否则,它会是同步的、受 CPU 限制的工作。这似乎没有任何重要的 CPU 工作,只是受 IO 限制的工作。那么,以一种不使用 `Task.Run` 而只是 `await` 是一种异步方法的方式来编写它是不是可能更好? (2认同)
  • 啊,我明白了。是的,使用 `Task.Run` 进行 I/O 工作是多余的,这里似乎确实如此。 (2认同)