码迷,mamicode.com
首页 > Windows程序 > 详细

C# Async Streams

时间:2021-07-02 15:58:46      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:reac   com   技术   rsa   load   stream   class   new   yield   

先看代码

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

执行结果如下图

技术图片

C# Async Streams

标签:reac   com   技术   rsa   load   stream   class   new   yield   

原文地址:https://www.cnblogs.com/microestc/p/14961522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!