Fix error CS4034: The await operator can only be used within an async lambda expression

When you call an async method, you have to use await operator to wait for the call to complete. You can not use await operator for an non-async method call. As example, let's say we have following async method.

public asyn Task DoSomething(MyObject o){
}

When you call this method, your code will look like below.

public async Task ConsumeSomething(){
 await DoSomething(o);
}

But when you have to consume this async method in a lambda expression, sometime we forget that a lamda expression is nothing but an anonymous function. It also needs to be marked with async keyword. See the following code, I have in my Blog framework.

var searchResultModels = 
     blogPosts.Select(b=>new BlogSearchResultModel{
        Id = b.Id, 
        SeName = await _urlRecordService.GetSeNameAsync
                 (b, b.LanguageId, ensureTwoPublishedLanguages: false) });

Above code will raise error CS4034: The await operator can only be used within an async lambda expression because of highlighted code above. I am trying to call an async method from lambda expression and did not mark my lambda expression as async. To fix this error, all you have to do is wrap your lambda expression with async expressions. Following code shows how to use async expression with lambda function.

var searchResultModels = 
     blogPosts.Select(async (b)=>new BlogSearchResultModel{
        Id = b.Id, 
        SeName = await _urlRecordService.GetSeNameAsync
                 (b, b.LanguageId, ensureTwoPublishedLanguages: false) });

Search

Social

Weather

7.7 °C / 45.9 °F

weather conditions Rain

Monthly Posts

Blog Tags