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

最佳答案

它仍然开放。您将需要明确处理/关闭连接,否则可能会出现内存或连接池问题。我建议您将上下文包装在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;
    }
}

10-04 14:21