इस तरह रीडर का उपयोग कर से बचने के लिए प्रयास करें:
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
कथन का उपयोग वस्तु और संसाधनों की मुक्त के सही निपटान सुनिश्चित करेगा।
यदि आप भूल जाते हैं तो आप कचरा कलेक्टर तक सफाई छोड़ रहे हैं, जिसमें कुछ समय लग सकता है।
आपको किसी भी नमूने में .lose() कथन की आवश्यकता नहीं है: इसे डिसस्पेक्ट() कॉल द्वारा नियंत्रित किया जाता है। –
ठीक है, मैंने कोड – Codebrain
में वैकल्पिक के रूप में चिह्नित किया है यह नमूना अंतर्निहित कनेक्शन बंद/डिस्पोजेड नहीं दिखाता है, जो सबसे महत्वपूर्ण बात है। – Joe