See the edits below to reproduce the behavior that I am describing in this issue.
The following program will never end because the yield return construct in C # calls the GetStrings() method indefinitely when an exception is thrown.
class Program { static void Main(string[] args) {
For this trivial example, I could obviously use return Enumerable.Empty<string>(); and the problem will disappear. However, in a more interesting example, I would expect the exception to be thrown once, and then the method will cease to be called and throw an exception in the method that "consumes" IEnumerable .
Is there any way to produce this behavior?
EDIT: ok, the problem is different than i thought. The program above does not end, and the foreach behaves like an infinite loop. The program below terminates and the exception is displayed on the console.
class Program { static void Main(string[] args) { try { foreach (var str in GetStrings()) { Console.WriteLine(str); } } catch (Exception e) { Console.WriteLine(e); } } private static IEnumerable<string> GetStrings() { throw new Exception(); yield break; } }
Why does the try ... catch make a difference in this case? This is very strange to me. Thanks to @AndrewKilburn for his reply already for pointing me to this.
EDIT # 2: On the command line, the program does the same thing in both cases. In Visual Studio Enterprise 2015, Update 2, whether compiling in Debug or Release, the behavior above is what I see. With try ... catch program ends with an exception, and without it, Visual Studio never closes the program.
EDIT 3: Fixed For me, the problem was resolved using @MartinBrown's answer. When I turn off the Visual Studio option under Debug> Preferences> Debug> General> Untie Call Stack on Unhandled Exceptions, this problem will disappear. When I check the box again, the problem will return.