简体   繁体   English

等待 foreach 块执行

[英]await foreach blocks execution

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)我正在学习 EFCore 和IAsyncEnumerable (现在使用 .net 5 和所有期望)并且我正在努力理解await foreach因为在我制作的一个测试用例中阻止执行(或者在我看来)

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;问题是“before”这句话写在最后,甚至不在中间; and the console is fully filled in block out of nowhere.并且控制台突然被完全填满了块。 The context is querying a localsql db.上下文正在查询 localsql 数据库。 Is there something I'm not understanding?有什么我不明白的吗?

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM