C# yield keyword relieve congest and consume at the same time with produce

using System.Threading;

namespace ConsoleApp57
{
    internal class Program
    {
        static void Main(string[] args)
        {
            PrintNumers();
            Console.WriteLine("Hello, World!");
        }

        static void PrintNumers()
        {
            var nums = GenEvenNumbers();
            foreach (var i in nums)
            {
                Console.WriteLine($"{i},{DateTime.Now.ToString("yyyyMMddHHmmss")}");
            }
        }

        static IEnumerable<int> GenEvenNumbers()
        {
            IEnumerable<int> arr = Enumerable.Range(0, Int32.MaxValue);
            foreach (int i in arr)
            {
                if(i%2==0)
                {
                    yield return i;
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

 

 

 

 

posted @ 2024-08-27 17:54  FredGrit  阅读(2)  评论(0编辑  收藏  举报