【发布时间】:2014-11-04 06:30:56
【问题描述】:
我正在尝试将文件列表复制到目录中。我正在使用异步/等待。 但是我一直收到这个编译错误
“await”运算符只能在异步 lambda 中使用 表达。考虑用“异步”标记这个 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);
}
}
}
谁能指出我在这里遗漏了什么?
【问题讨论】:
-
你没有用
async关键字标记lambda?基本上,如果你在Task.Run中提取了 lambda,它就不是async方法,所以你不能等待结果。 -
await Task.Run<int>(() => ...-- lambda 不是async。 -
这应该不带 lambda 或
Task.Run,因为它只是 IO 绑定的工作。有关示例解决方案,请参阅 pastebin.com/p83gkkTk(我会将此作为答案发布,但它已经关闭)。 -
@TimS。谢谢,是的,我同意。
标签: c# async-await .net-4.5