Loading

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

上部分执行结果如下图

注释 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);
            }
        }

执行结果如下图

posted @ 2021-07-02 00:15  microestc  阅读(80)  评论(0编辑  收藏  举报