ฉันกำลังทำงานกับรหัสเดิมที่นี่และมีหลายกรณีSqlDataReader
ที่ไม่เคยปิดหรือกำจัดทิ้ง การเชื่อมต่อถูกปิด แต่ฉันไม่แน่ใจว่าจำเป็นต้องจัดการเครื่องอ่านด้วยตนเองหรือไม่
สิ่งนี้อาจทำให้ประสิทธิภาพการทำงานช้าลงหรือไม่
ฉันกำลังทำงานกับรหัสเดิมที่นี่และมีหลายกรณีSqlDataReader
ที่ไม่เคยปิดหรือกำจัดทิ้ง การเชื่อมต่อถูกปิด แต่ฉันไม่แน่ใจว่าจำเป็นต้องจัดการเครื่องอ่านด้วยตนเองหรือไม่
สิ่งนี้อาจทำให้ประสิทธิภาพการทำงานช้าลงหรือไม่
คำตอบ:
พยายามหลีกเลี่ยงการใช้โปรแกรมอ่านแบบนี้:
SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
reader.Close(); // <- too easy to forget
reader.Dispose(); // <- too easy to forget
connection.Close(); // <- too easy to forget
ให้ห่อโดยใช้คำสั่ง:
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
} // reader closed and disposed up here
} // command disposed here
} //connection closed and disposed here
คำแถลงการใช้จะช่วยให้มั่นใจได้ว่ามีการกำจัดวัตถุอย่างถูกต้องและการปลดปล่อยทรัพยากร
หากคุณลืมคุณจะทิ้งการทำความสะอาดไปยังคนเก็บขยะซึ่งอาจใช้เวลาสักครู่
โปรดทราบว่าการกำจัด SqlDataReader ที่สร้างอินสแตนซ์โดยใช้ SqlCommand.ExecuteReader () จะไม่ปิด / กำจัดการเชื่อมต่อพื้นฐาน
มีสองรูปแบบทั่วไป ในขั้นแรกผู้อ่านจะเปิดและปิดภายในขอบเขตของการเชื่อมต่อ:
using(SqlConnection connection = ...)
{
connection.Open();
...
using(SqlCommand command = ...)
{
using(SqlDataReader reader = command.ExecuteReader())
{
... do your stuff ...
} // reader is closed/disposed here
} // command is closed/disposed here
} // connection is closed/disposed here
บางครั้งการใช้วิธีการเข้าถึงข้อมูลเพื่อเปิดการเชื่อมต่อและส่งคืนเครื่องอ่านก็สะดวก ในกรณีนี้สิ่งสำคัญคือต้องเปิดเครื่องอ่านที่ส่งคืนโดยใช้ CommandBehavior.CloseConnection ดังนั้นการปิด / ทิ้งเครื่องอ่านจะเป็นการปิดการเชื่อมต่อที่สำคัญ รูปแบบมีลักษณะดังนี้:
public SqlDataReader ExecuteReader(string commandText)
{
SqlConnection connection = new SqlConnection(...);
try
{
connection.Open();
using(SqlCommand command = new SqlCommand(commandText, connection))
{
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch
{
// Close connection before rethrowing
connection.Close();
throw;
}
}
และรหัสการโทรเพียงแค่ต้องการกำจัดผู้อ่านดังนั้น:
using(SqlDataReader reader = ExecuteReader(...))
{
... do your stuff ...
} // reader and connection are closed here.
using
s ให้เรียกทิ้งในfinally {}
บล็อกหลังจากจับได้ วิธีการเขียนคำสั่งที่ประสบความสำเร็จจะไม่ถูกปิดหรือกำจัด
เพียงห่อ SQLDataReader ของคุณด้วยคำสั่ง "ใช้" ที่ควรดูแลปัญหาส่วนใหญ่ของคุณ