深入理解 c# 第六章 在try/finally 一道工作的yield break

时间:2020-12-26 18:19:58
    class YieldBreakAndTryFinally
    {
        static IEnumerable<int> CountWithTimeLimit(DateTime limit)
        {
            try
            {
                for (int i = 1; i <= 100; i++)  //迭代到100  也会执行异常
                {
                    if (DateTime.Now >= limit) 
                    {
                        yield break;  //这句执行就执行 finally里面的语句
                    }
                    yield return i;
                }
            }
            finally
            {
                Console.WriteLine("Stopping!");  //不管循环是否结束都执行
            }
        }

        static void Main()
        {
            DateTime stop = DateTime.Now.AddSeconds(2);  //当前时间 +2 s
            foreach (int i in CountWithTimeLimit(stop))  //foreach循环结束 也会执行异常
            {
                Console.WriteLine("Received {0}", i);
                Thread.Sleep(300);
            }
        }
    }


输出

Received 1
Received 2
Received 3
Received 4
Received 5
Received 6
Received 7
Stopping!