zoukankan      html  css  js  c++  java
  • C# 实践 2 async 关键字

    参考:

    https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/async

    https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/

    "这就是此语法的目标:支持读起来像一连串语句的代码,但会根据外部资源分配和任务完成时间以更复杂的顺序执行。 "

    实现:代码以串行的方式书写,却可以不按照串行执行。异步。

    代码:

    private static async Task<bool> RunStreamingDemo(string host, int port)
    {
    ...
    }
    

     

    代码:

    static async Task Main(string[] args)
    {
        Coffee cup = PourCoffee();
        Console.WriteLine("coffee is ready");
        var eggsTask = FryEggsAsync(2);
        var baconTask = FryBaconAsync(3);
        var toastTask = MakeToastWithButterAndJamAsync(2);
    
        var allTasks = new List<Task>{eggsTask, baconTask, toastTask};
        while (allTasks.Any())
        {
            Task finished = await Task.WhenAny(allTasks);
            if (finished == eggsTask)
            {
                Console.WriteLine("eggs are ready");
            }
            else if (finished == baconTask)
            {
                Console.WriteLine("bacon is ready");
            }
            else if (finished == toastTask)
            {
                Console.WriteLine("toast is ready");
            }
            allTasks.Remove(finished);
        }
        Juice oj = PourOJ();
        Console.WriteLine("oj is ready");
        Console.WriteLine("Breakfast is ready!");
    
        async Task<Toast> MakeToastWithButterAndJamAsync(int number)
        {
            var toast = await ToastBreadAsync(number);
            ApplyButter(toast);
            ApplyJam(toast);
            return toast;
        }
    }
    

      

    此最终代码是异步的。 它更为准确地反映了一个人做早餐的流程。 将上述代码与本文中的第一个代码示例进行比较。 阅读代码时,核心操作仍然很明确。 你可以按照阅读本文开始时早餐制作说明的相同方式阅读此代码。 asyncawait 的语言功能支持每个人做出转变以遵循这些书面指示:尽可能启动任务,不要在等待任务完成时造成阻塞

     

  • 相关阅读:
    cnblog项目--20190309
    django js引入失效问题
    Python老男孩 day16 函数(六) 匿名函数
    Python老男孩 day16 函数(五) 函数的作用域
    Python老男孩 day15 函数(四) 递归
    Python老男孩 day15 函数(三) 前向引用之'函数即变量'
    Python老男孩 day15 函数(二) 局部变量与全局变量
    Python老男孩 day14 函数(一)
    Python老男孩 day14 字符串格式化
    Python老男孩 day14 集合
  • 原文地址:https://www.cnblogs.com/alexYuin/p/12397329.html
Copyright © 2011-2022 走看看