Initial Statement
I would like to call asynchronously an operation to which I pass a delegate as a parameter (details below). The compiler gives me an error. Could someone point me in the right direction?
Async function:
private async Task<Route> FindRouteAsync(Destination Destination,
Func<Destination, bool> predicate){...
List<Destination> _Destinations = __Route.Destinations.Where(predicate).ToList();
...}
Calling code:
private async Task<List<Route>> FindRoutesAsync(Destination[] Destinations){...
Route _DestinationRoute = await FindRouteAsync(__Destination,
d => d == __Destination);
...}
The compilation error:
The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
Updated Statement 1
@svick, @Stephen Cleary: Thank you guys! You were right, the problem was just as you expected in an outer loop: What I had was (simplified):
Parallel.ForEach<Destination>(Destinations, __Destination =>
{
Route _DestinationRoute = await FindRouteAsync(__Destination,
d => d == __Destination);
}
Because of this lambda expression __Destination => {...}
the code wouldn't compile. I turned it into __Destination => async {...}
and now it works.
Now it looks like this:
Parallel.ForEach<Destination>(Destinations, async __Destination =>
{
try
{
// First, try to find an exact match
Route _DestinationRoute = await FindRouteAsync(__Destination, d => d == __Destination);
if (_DestinationRoute.ConnectionId != 0)
{ _DestinationRoutes.Enqueue(_DestinationRoute); }
...
}
catch...
});
So I was just looking at the wrong lambda expression in my code. The other one was causing all the fuss. Thank you again! Lesson learned: "don't jump so fast to assumptions in the future".
PS: it's my first time here and maybe you can help me with giving credit where is due. I think the contributions from svick, Stephen Cleary and (in perspective) Javalsu were helpful. What do I do now? In all fairness, svick's comment led me to the code analysis that showed me the error in the end.
Updated Statement 2
It seems the whole construct of Parallel.ForEach
with await
inside the loop was flawed and the solution had poor chances of success. More details can be found here: Nesting await in Parallel foreach.