填充字典后,我的SQL连接是否仍然打开

时间:2010-09-08 22:59:17

标签: c# linq-to-sql connection-string

在下面的代码示例中,一旦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;
            }
        }

1 个答案:

答案 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;
    }
}