fork(1) download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. public class Test
  6. {
  7. public static void Main(string[] args)
  8. {
  9. foreach (var i in new DangerousEnumerable())
  10. {
  11. Console.WriteLine(i);
  12. break; // consumer decides to abort
  13. }
  14. }
  15. }
  16.  
  17. public class Resource : IDisposable
  18. {
  19. public Resource()
  20. {
  21. Console.WriteLine("Resource acquired!");
  22. }
  23.  
  24. public void Dispose()
  25. {
  26. Console.WriteLine("Resource disposed!");
  27. }
  28. }
  29.  
  30. public class DangerousEnumerable : IEnumerable<int>
  31. {
  32. public IEnumerator<int> GetEnumerator()
  33. {
  34. using (new Resource())
  35. {
  36. yield return 1;
  37. yield return 2;
  38. }
  39. Console.WriteLine("Finished!");
  40. }
  41.  
  42. IEnumerator IEnumerable.GetEnumerator()
  43. {
  44. return GetEnumerator();
  45. }
  46. }
Success #stdin #stdout 0.03s 33904KB
stdin
Standard input is empty
stdout
Resource acquired!
1
Resource disposed!