繁体   English   中英

异步并等待,期望在主程序中不阻塞

[英]async and await, expecting non-blocking in main

根据我对async关键字的理解,结合使用await可以为实际需要异步操作的结果创建连续点,从而允许在此期间进行其他工作。

那为什么下面的阻塞呢? 我希望Nothing to do while the awaits complete, expecting this line to come first. 是输出到控制台的第一行。

tasks.cs

public static async Task Execute()
{
    var sw = new Stopwatch();
    sw.Start();
    await Foo();
    sw.Stop();
    Console.WriteLine($"Execute completed in {sw.ElapsedMilliseconds}ms.");
}

private static async Task Foo()
{
    var tasks = Enumerable.Range(0, 5).Select(x =>
    {
        return Task.Factory.StartNew((b) =>
        {
            Thread.Sleep(100);
            int value = (int) b;
            Console.WriteLine($"Task ran on thread: {Thread.CurrentThread.ManagedThreadId}");
            return value * value;
        }, x);
    }).ToArray();

    await Task.WhenAll(tasks);
}

在主叫

static async Task Main(string[] args)
{
    await Tasks.Execute();
    var result = await LongRunningOperation();
    Console.WriteLine("Nothing to do while the awaits complete, expecting this line to come first.");
    Console.WriteLine($"Long running operation result: {result}");
}

private static async Task<int> LongRunningOperation()
{
    var sw = new Stopwatch();
    sw.Start();
    var res = await Task.Factory.StartNew(() =>
    {
        Thread.Sleep(10000);
        Console.WriteLine($"Long running operation completed on thread {Thread.CurrentThread.ManagedThreadId}");
        return 10000;
    });
    sw.Stop();

    return res;
}

输出以下内容:

Task ran on thread: 7
Task ran on thread: 4
Task ran on thread: 3
Task ran on thread: 5
Task ran on thread: 6
Execute completed in 113ms.
Long running operation completed on thread 9
Nothing to do while the awaits complete, expecting this line to come first.
Long running operation result: 10000

这意味着我在这种情况下处于阻塞状态,并且一切都按顺序链接在一起……我不明白什么?

Microsoft Docs

将await运算符应用于异步方法中的任务,以在该方法的执行中插入一个暂停点,直到等待的任务完成

通过写var result = await LongRunningOperation(); 您将暂停任何进一步的操作,直到LongRunningOperation完成。

如果您将Main重写为如下所示:

static async Task Main(string[] args)
{
    var longTask = LongRunningOperation();
    Console.WriteLine("Nothing to do while the awaits complete, expecting this line to come first.");
    var result = await longTask;
    Console.WriteLine($"Long running operation result: {result}");
}

然后您的程序将打印预期的行, 然后等待任务完成,然后再尝试输出结果。

暂无
暂无

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

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