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!