c# - 'await' 运算符只能与异步 lambda 表达式一起使用

标签 c# async-await .net-4.5

<分区>

我正在尝试将文件列表复制到目录中。我正在使用异步/等待。 但是我遇到了这个编译错误

The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

我的代码是这样的

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);
        }
    }

}

谁能指出我在这里遗漏了什么?

最佳答案

int processCount = await Task.Run<int>(() =>

应该是

int processCount = await Task.Run<int>(async () =>

请记住,lambda 只是定义方法 的简写。因此,您的外部方法是 async,但在这种情况下,您尝试在 lambda 中使用 await(这是一种不同方法你的外部方法)。因此,您的 lambda 也必须标记为 async

关于c# - 'await' 运算符只能与异步 lambda 表达式一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25768284/

相关文章:

C#:从 IEnumerable 获取随机值的优雅代码

c# - 如何检查我的文件夹中是否至少有一个文件* .bak?

c# - HttpClient.GetAsync(...) 在使用 await/async 时永远不会返回

c# - 反 xsrf token 验证失败

c# - 使用 { get; 实现只读属性}

C#:字典 TryGetValue 创建实例而不是获取引用

c# - EntityFramework 6 DatabaseFirst 禁用延迟加载

javascript - 如何在 GAS 功能真正结束后运行功能?

c# - 在未处理的异常处理程序中异步写入文件

.net - WCF WSDL 摆脱 qXX 命名空间