“await"运算符只能与异步 lambda 表达式一起使用 [英] The 'await' operator can only be used with an async lambda expression
问题描述
我正在尝试将文件列表复制到目录中.我正在使用异步/等待.但我一直收到这个编译错误
I'm trying to copy a list of files to a directory. I'm using async / await. But I've been getting this compilation error
'await' 操作符只能在异步 lambda 中使用表达.考虑用async"标记这个 lambda 表达式修饰符.
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);
}
}
}
请有人指出我在这里遗漏了什么吗?
Pls can anyone point out what am I missing here ?
推荐答案
int processCount = await Task.Run<int>(() =>
应该
int processCount = await Task.Run<int>(async () =>
请记住,lambda 只是定义方法 的简写.因此,您的外部方法是 async
,但在这种情况下,您尝试在 lambda 中使用 await
(与你的外部方法).因此,您的 lambda 也必须标记为 async
.
Remember that a lambda is just shorthand for defining a method. So, your outer method is async
, but in this case you're trying to use await
within a lambda (which is a different method than your outer method). So your lambda must be marked async
as well.
这篇关于“await"运算符只能与异步 lambda 表达式一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!