在下面的代码示例中,一旦ListOfLists方法完成,我的数据上下文连接是否会保持打开状态?我是否需要明确关闭它,或者它是否保持打开状态并可用于其他方法。
public static Dictionary<int, string > ListOfLists()
{
try
{
ListDataDataContext db = new ListDataDataContext(GetConnectionString("Master"));
return db.ListMatchingHeaders
.Select(r => new { r.ListRecNum, r.ListName })
.ToDictionary(t => t.ListRecNum, t => t.ListName);
}
catch (Exception)
{
MessageBox.Show("Could not connect to database, please check connection and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
答案 0 :(得分:2)
它仍然是开放的。您需要明确地处置/关闭连接,否则可能存在内存或连接池问题。我建议您将上下文包装在using
块周围。
public static Dictionary<int, string> ListOfLists()
{
try
{
using (ListDataDataContext db = new ListDataDataContext(GetConnectionString("Master")))
{
return db.ListMatchingHeaders
.Select(r => new { r.ListRecNum, r.ListName })
.ToDictionary(t => t.ListRecNum, t => t.ListName);
}
}
catch (Exception)
{
MessageBox.Show("Could not connect to database, please check connection and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}