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
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
This is what my code looks like
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 ?
The "await is only valid in async functions" error occurs when the await keyword is used inside of a function that wasn't marked as async . To use the await keyword inside of a function, mark the directly enclosing function as async .
Lambda functions can be invoked either synchronously or asynchronously, depending upon the trigger. In synchronous invocations, the caller waits for the function to complete execution and the function can return a value.
C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.
int processCount = await Task.Run<int>(() =>
Should be
int processCount = await Task.Run<int>(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With