code_junkie

Using yield to iterate over a datareader might not close the connection?

Nov 10th, 2011
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. public IEnumerable<object> ExecuteSelect(string commandText)
  2. {
  3. using (IDbConnection connection = CreateConnection())
  4. {
  5. using (IDbCommand cmd = CreateCommand(commandText, connection))
  6. {
  7. connection.Open();
  8. using (IDbDataReader reader = cmd.ExecuteReader())
  9. {
  10. while(reader.Read())
  11. {
  12. yield return reader["SomeField"];
  13. }
  14. }
  15. connection.Close();
  16. }
  17. }
  18. }
  19.  
  20. foreach(object obj in ExecuteSelect(commandText))
  21. {
  22. break;
  23. }
  24.  
  25. class Program
  26. {
  27. static void Main(string[] args)
  28. {
  29. foreach (int v in getValues())
  30. {
  31. Console.WriteLine(v);
  32. }
  33. Console.ReadKey();
  34.  
  35. foreach (int v in getValues())
  36. {
  37. Console.WriteLine(v);
  38. break;
  39. }
  40. Console.ReadKey();
  41. }
  42.  
  43. public static IEnumerable<int> getValues()
  44. {
  45. using (TestDisposable t = new TestDisposable())
  46. {
  47. for(int i = 0; i<10; i++)
  48. yield return t.GetValue();
  49. }
  50. }
  51. }
  52.  
  53. public class TestDisposable : IDisposable
  54. {
  55. private int value;
  56.  
  57. public void Dispose()
  58. {
  59. Console.WriteLine("Disposed");
  60. }
  61.  
  62. public int GetValue()
  63. {
  64. value += 1;
  65. return value;
  66. }
  67. }
Add Comment
Please, Sign In to add comment