Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'await' operator can only be used with an async lambda expression [duplicate]

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 ?

like image 255
abhilash Avatar asked Sep 10 '14 14:09

abhilash


People also ask

Why await can only be used in async function?

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 .

Is it possible to make a lambda that executes asynchronously?

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.

Does async await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.


1 Answers

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.

like image 71
Stephen Cleary Avatar answered Sep 17 '22 19:09

Stephen Cleary