The following should return "C", but it returns "B"
using System.Data.Entity;
//...
var state = "A";
var qry = (from f in db.myTable select f);
await qry.ForEachAsync(async (myRecord) => {
await DoStuffAsync(myRecord);
state = "B";
});
state = "C";
return state;
It doesn't wait for DoStuffAsync to complete, state="C"
runs through and then later state="B"
executes (because inside it is still awaiting).
That's because the implementation of ForEachAsync doesn't await the delegated action
see https://github.com/mono/entityframework/blob/master/src/EntityFramework/Infrastructure/IDbAsyncEnumerableExtensions.cs#L19
But that is because, you can't await an action, the delegate needs to be a Func which returns a Task - see How do you implement an async action delegate method?
Therefore, until Microsoft provides a signature which includes a Func delegate and calls it with await, you'll have to roll your own extension method. I'm using the following at the moment.
With this, the original test code in your OP will work as expected.