4
การเชื่อมต่อฐานข้อมูลจะถูกปิดหรือไม่ถ้าเราให้ผลแถวของ data datader และไม่อ่านบันทึกทั้งหมด?
ในขณะที่ทำความเข้าใจวิธีการyieldทำงานของคำหลักฉันเจอlink1และlink2บน StackOverflow ซึ่งสนับสนุนการใช้งานyield returnในขณะวนซ้ำ DataReader และเหมาะสมกับความต้องการของฉันเช่นกัน แต่มันทำให้ฉันสงสัยว่าเกิดอะไรขึ้นถ้าฉันใช้yield returnดังที่แสดงด้านล่างและถ้าฉันไม่ทำซ้ำใน DataReader ทั้งหมดการเชื่อมต่อฐานข้อมูลจะเปิดตลอดไปหรือไม่ IEnumerable<IDataRecord> GetRecords() { SqlConnection myConnection = new SqlConnection(@"..."); SqlCommand myCommand = new SqlCommand(@"...", myConnection); myCommand.CommandType = System.Data.CommandType.Text; myConnection.Open(); myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); try { while (myReader.Read()) { yield return myReader; } } finally { myReader.Close(); } } void AnotherMethod() { foreach(var …