C# Async Streams

先看代码

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AsyncStream
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var product = new Productor();

            var numbers = await product.GetNumbersAsync();
            foreach(var number in numbers)
            {
                Console.WriteLine(number);
            }

            return;

            await foreach(var number in product.EnumerateNumbersAsync())
            {
                Console.WriteLine(number);
            }
        }
    }

    public class Productor
    {
        public async Task<IEnumerable<int>> GetNumbersAsync()
        {
            List<int> numbers = new();
            for (int tens = 0; tens < 10; tens++)
            {
                Console.WriteLine("get some numbers.");
                for (int digit = 0; digit < 10; digit++)
                {
                    numbers.Add(tens * 10 + digit);
                }
                Console.WriteLine("making next request...");
                await Task.Delay(1000);
            }
            return numbers;
        }

        public async IAsyncEnumerable<int> EnumerateNumbersAsync()
        {
            for (int tens = 0; tens < 10; tens++)
            {
                Console.WriteLine("get some numbers.");
                for (int digit = 0; digit < 10; digit++)
                {
                    yield return tens * 10 + digit;
                }
                Console.WriteLine("making next request...");
                await Task.Delay(1000);
            }
        }
    }
}

上部分执行结果如下图
C# Async Streams

注释 main 函数 return ;之前的代码

        static async Task Main(string[] args)
        {
            var product = new Productor();

            // var numbers = await product.GetNumbersAsync();
            // foreach(var number in numbers)
            // {
            //     Console.WriteLine(number);
            // }

            // return;

            await foreach(var number in product.EnumerateNumbersAsync())
            {
                Console.WriteLine(number);
            }
        }

执行结果如下图

C# Async Streams

C# Async Streams

上一篇:阿里云PHP Composer全量镜像正式上线!(附下载地址)


下一篇:《Web前端开发最佳实践》——3.4 停止使用不标准的标签和属性,简化HTML代码