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
.
归档时间: |
|
查看次数: |
26016 次 |
最近记录: |