C# Async Streams

时间:2021-07-02 15:58:46   收藏:0   阅读:0

先看代码

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

执行结果如下图

技术图片

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!