await foreach blocks execution

759 Views Asked by At

I'm learning EFCore and IAsyncEnumerable (now with .net 5 and all the expectation) and I'm struggling understanding await foreach because in one test case I made is blocking execution (or that seems to me)

static async Task Main()
{
    await Test().ConfigureAwait(false);

    Debug.WriteLine("this should happen before, isn't it?");
    Console.ReadKey();
}

static async Task Test()
{
    using var ctx = new MyContext();

    var testDbset = ctx.Entries;

    await foreach (var entry in testDbset.ConfigureAwait(false))
    {
        Console.WriteLine(entry.ToString());
    }
}

The problem is the "before" sentence is written the last, not even in the middle; and the console is fully filled in block out of nowhere. The context is querying a localsql db. Is there something I'm not understanding?

1

There are 1 best solutions below

1
On

If you want the message to appear first, don't await the task till after it has been printed.

static async Task Main()  
{
    var task = Test().ConfigureAwait(false);
    Debug.WriteLine("this should happen before, isn't it?");
    await task;
    Console.ReadKey();
}