简体   繁体   中英

c# async await strange warning CS1998: This async method lacks 'await' operators

i'm new to async programming, i get the below warning in this method, does somebody knows why this happens? Thank you very much.

   public async Task<List<T1>> StartSearchAsync()
    {
        ....other code

        searchRequests.ForEach(async s => {
            products.AddRange(await SinglePageSearch(s));
        });

        return products;
    }

warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Your await is within a lambda expression, which is another function entirely to your StartSearchAsync method.

In fact you should not be passing an async delegate to List<T>.ForEach , as that converts the delegate to async void , which is undesirable because the calling method cannot wait for the delegates to complete.

A better option would be to use Enumerable.Select , in combination with Task.WhenAll :

public async Task<List<T1>> StartSearchAsync()
{
    ....other code
    
    var tasks = searchRequests.Select(SinglePageSearch);
    var results = await Task.WhenAll(tasks);

    foreach (result in results) products.AddRange(result);

    return products;
}

Using this approach, Task.WhenAll enumerates the Task s generated by Select , and creates another Task that completes when each SinglePageSearch has completed.

Now StartSearchAsync can await their completion.

And if products is simply an empty list being used to amalgamate the results, you can simplify further:

public async Task<List<T1>> StartSearchAsync()
{
    ....other code
    
    var results = await Task.WhenAll(searchRequests.Select(SinglePageSearch));

    return results.SelectMany(x => x).ToList();
}

The compiler tells you that you can safely remove the async keyword from the method signature since you are not using the await keyword directly inside the StartSearchAsync() method.

You are indeed using await in the delegate that you pass for ForEach but this doesn't affect the compilation of the StartSearchAsync() method.

The async keyword is only used to enable you to await methods in the method or delegate that you mark as async .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM