Why doesn't a method containing an async lambda need to be Async itself?
An async lambda is just a simple way of creating a delegate which is asynchronous. There's nothing to say that the method which contains it has to be doing anything asynchronous itself - and any await
expressions within the lambda expression won't make the containing method wait (unless it's awaiting a task which happens to rely on the delegate, of course).
Basically the lambda expression is expressing some asynchronous code - it's not executing the asynchronous code itself... so the containing method isn't necessarily executing asynchronously.
Yes, the example you've given is a misuse of async lambdas - but making the method async wouldn't improve matters at all, and it would simply be misleading.
EDIT: As an alternative way of thinking about it, consider this refactoring of your original code:
public void SaveSome()
{
Action<int> action = SaveRepAsync;
Array.ForEach(Enumerable.Range(0,3).ToArray(), action);
}
private static async void SaveRepAsync(int x)
{
await SaveRep();
}
The SaveSome
method has nothing asynchronous about it - only the SaveRepAsync
method does... so that's what requires the async
modifier. This really is just a tiny refactoring of your code (the sort of refactoring the compiler would do, effectively). If you wanted every method containing an async lambda to have the async modifier, that's like saying that in the above code, SaveSome
should have the modifier too... which would make no sense, IMO.
You can only await
an async
method in an async
method, but you can still call them in a non-async method, like you're doing above - in this case, it's more a "fire and forget"