【问题标题】:Task Control Flow任务控制流
【发布时间】:2020-07-06 22:03:03
【问题描述】:

我已经使用 task 和 async/await 结构工作了几天,但流程有时会让我感到厌烦。也许是因为我正在以同步的方式考虑它。我有以下代码:

static void Main(string[] args)
    {
        Console.WriteLine("Call a async method with no result from non-async method....!");

        Task myTask = DoSomethingAsync();
        myTask.Wait();
        myTask.ContinueWith(t => {
            Console.WriteLine("Inside continuation.");
        });

        Console.WriteLine("Program completed...");

        Console.WriteLine("Completed...");
    }
    static async Task DoSomethingAsync()
    {
        Console.WriteLine("Inside DoSomething; no return value.");
        await Task.Delay(5000);
        Console.WriteLine("DoSomething method is completed...");
    }

我的问题是,当调用 Wait 时,我假设编译器正在等待我的 DoSomethingAsync 方法完成,然后继续执行;但是,直到“程序已完成”和“已完成”文本打印到屏幕后才会执行继续。在调试模式下运行时,一旦 DoSomethingAsync 方法完成,调试器就会返回继续;但实际上并没有。这是怎么回事?是因为启动了另一个任务吗?如果是这样,为什么等待之后任务没有开始?

【问题讨论】:

    标签: asynchronous task


    【解决方案1】:

    通过在 continuation 上放置等待,以便代码现在读取为

      myTask.ContinueWith(t =>
            {
                Console.WriteLine("Inside continuation.");
            }).Wait();
    

    这将允许在调用程序完成之前继续完成。

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多