尽量避免使用这样的读者:
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 forgetreader.Dispose(); // <- too easy to forgetconnection.Close(); // <- too easy to forget
相反,将它们包装在using语句中:
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
using语句将确保正确处置对象和释放资源。
如果您忘记了,则将清理工作留给垃圾收集器,这可能需要一段时间。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)